Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes use comparator in jdk1.4 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "use comparator in jdk1.4" Watch "use comparator in jdk1.4" New topic

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é

Joined: Nov 24, 2005
Posts: 14688

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:
subject: use comparator in jdk1.4
It's not a secret anymore!