I have the following code. I was expecting Arrays.asList(LocalDate.of(2014, 1, 1), LocalDate.of(2015, 2, 2))
to convert into the list of LocalDate
. But I am getting compile time error in max(dates)
. What might be the cause of this error?
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class C {
public static <T extends Comparable<T>> T max(List<T> d) {
if (d.size() == 0) {
return null;
}
T maxValue = d.get(0);
for (T temp : d) {
if (maxValue.compareTo(temp) < 0) {
maxValue = temp;
}
}
return maxValue;
}
public static void main(String[] args) {
List<LocalDate> dates = new ArrayList<>();
dates.add(LocalDate.of(2015, 9, 15));
dates.add(LocalDate.of(2010, 9, 1));
max(dates); //This line generates compile error.
max(Arrays.asList(LocalDate.of(2014, 1, 1), LocalDate.of(2015, 2, 2)));
}
}
Compile Time Error: The method max(List) in the type C is not applicable for the arguments (List)
LocalDate
implements Comparable<ChronoLocalDate>
and not Comparable<LocalDate>
Therefore change:
public static <T extends Comparable<T>> T max(List<T> d) { ... }
to:
public static <T extends Comparable<? super T>> T max(List<T> d) { ... }