File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections.sort() throws ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections.sort() throws ClassCastException" Watch "Collections.sort() throws ClassCastException" New topic

Collections.sort() throws ClassCastException

naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384

Hi frneds,

i am little confused about Collections.sort() , when does it throws ClassCastException (CCE). As java api suggest that it is only throws classCastException when elements are not "mutually comparable" ?

but i found that , there might be two cases in which method throws CCE :

1. when elements does not implement Comparable<E> interface in line 9.

2. As java api says , when underlying collection elements are not mutually comparable in line 3
in this case each element implements comparable<E> interface but elements are not mutually COMPATABILE.

Please throw some light on the case 1.

what does mutually comparable means ?
does it mean "compatible elements " or elements that implements comparable<E> interface.

Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

"Mutually comparable" means that they can be compared with each other. More formally, it means that for any two elements in the collection, say x and y, you can call x.compareTo(y).

So that covers both your examples. If you've got an instance of a class that doesn't implement Comparable, then obviously that's not going to work. The sort method will first cast it to Comparable, and this will throw the exception. In the second case, although they both implement Comparable they can't be compared with each other because you've got a Comparable<Integer> and a Comparable<String>.
I agree. Here's the link:
subject: Collections.sort() throws ClassCastException
It's not a secret anymore!