4

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)
peskal
  • 1,213
  • 1
  • 12
  • 28
  • Without seeing code it's going to be awfully hard to tell you what's wrong. Post the definition of both `Flub` and the comparator. – Jim Garrison Jul 28 '11 at 23:57

1 Answers1

9

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.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • 1
    ...and it is! I would have expected a NullPointerException. Silly me. – peskal Jul 29 '11 at 00:01
  • @ColinD Thank you. I spent an hour following my code around, confirming that I had indeed supplied a Comparator to the TreeSet I was using, and only your answer here made me check that it was not in fact null. I was stupidly declaring a static comparator **after** the static singleton instance of the class. So the singleton was seeing a null value for the Comparator at time of construction of the TreeSet. – Bobulous Sep 04 '12 at 19:09