This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori 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 | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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
It is sorta covered in the JavaRanch Style Guide.
subject: use comparator in jdk1.4
It's not a secret anymore!