I am calling Collections.sort() on an ArrayList using a Comparator that I declared earlier.
ArrayList<Employee> list = new ArrayList<Employee>();
Comparator<Employee> comparator = new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
}
};
...
Collections.sort(list, comparator);
For some reason, sort is trying to cast the elements of my ArrayList as Comparables, even though I passed a Comparator. Why might this be happening?
If it's of any use, here is my stacktrace
Exception in thread "Thread-3" java.lang.ClassCastException: processing.app.EmployeeManager$PrettyOkayEmpolyee cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at foobar.Main.doSomeSorting(Main.java:140)
...
at java.lang.Thread.run(Unknown Source)
The Comparator
you passed is probably null
.
The Javadoc states:
@param
c
the comparator to determine the order of the list. Anull
value indicates that the elements' natural ordering should be used.
So it's going to assume the arguments are Comparable
if the Comparator
is null
. The code in Arrays.sort
is consistent with this. I think it really ought to throw a NPE if the Comparator
is null
, but it's part of the contract of the method and so can't be changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With