What can cause Collections.sort (List <T>, Comparator <? Super T>) to throw a ClassCastException?

I call Collections.sort () on an ArrayList using the Comparator 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, sorting is trying to pass the elements of my ArrayList as Comparables, although I passed Comparator. Why can this happen?

If applicable, 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) 
+4
source share
1 answer

The past Comparator is probably null .

Javadoc says:

@param c comparator for determining the order of the list. A null value indicates that the natural order of the elements must be used.

Thus, it is assumed that the arguments are Comparable if Comparator is null . The code in Arrays.sort is consistent with this. I think that you really need to throw NPE if Comparator null , but this is part of the method contract and therefore cannot be changed.

+9
source

All Articles