Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 307
peskal Avatar asked Jan 20 '23 02:01

peskal


1 Answers

The Comparator you passed is probably null.

The Javadoc states:

@param c the comparator to determine the order of the list. A null 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.

like image 122
ColinD Avatar answered Feb 13 '23 17:02

ColinD