• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.sort() throws ClassCastException

 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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>.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic