This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes use comparator in jdk1.4 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "use comparator in jdk1.4" Watch "use comparator in jdk1.4" New topic
Author

use comparator in jdk1.4

FY Hsieh
Ranch Hand

Joined: Aug 07, 2006
Posts: 73
I have class like



It compiles but gives run time ClassCastException error "Student can not be casted to Comparable". I am not using Comparable. I am using Comparator.
Why do I get that error ? what's the best and easy way to fix assuming I still use Comparator and Arraylist ?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14685
    
  16

If you want to make Students comparable, you should implement the Comparable interface instead. If you insist on making the Student class to be a Comparator as well, you have to use the sort method the following way :

This will tell the Collections class to use a new comparator to compare the Students. That looks awkward though. You should use Comparable instead.


[My Blog]
All roads lead to JavaRanch
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: use comparator in jdk1.4
 
Similar Threads
sorting using comparator interface
determine the input type of the value of the function parameter map
BinarySearch Doubt
Sorting ArrayList
another question about using comparator