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 TreeSet & Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet & Comparator" Watch "TreeSet & Comparator" New topic

TreeSet & Comparator

Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Source: Inquisition

There is a ClassCastException on running this code which I thought is because of not properly setting the 'testNumber' instance variable, and compare() uses this unset variable for comparison.

So, I modified the code like this:

Even now, the same exception occurs. A TreeSet can have objects whose class implements Comparator interface, right? Then what is the issue here?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226

yes a TreeSet can have objects whose class implements the Comparator interface, but you need to pass the class object to the Tree set. If you do something like this in main:

you won't get the exceptions as you are telling the TreeSet how you want to sort the set via the variable 'q'

If you had changed your code to implement Comparable and declare the compareTo() method then you won't need to pass anything to the TreeSet.

Hope that makes sense

My Path to SCJP Certification My Path to SCWCD Certification
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231
A small change in the constructor of TreeSet()

Your original code will run with the above change.
The rule being simple. If you want to sort using a comparator then you need to pass the comparator in the TreeSet's constructor. Otherwise by default TreeSet assumes that the objects in the Set implement the Comparable interface.

Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Yes. I got it..
Thanks Wouter,Santiago and Harvinder !!!
meera kanekal
Ranch Hand

Joined: Feb 13, 2005
Posts: 75
Could you please post the correct code. I was also trying to test the code you posted with the modifications suggested by the others.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710

See what harvinder says!

TreeSet constructor accepts Comparator (A class that implements Comparator).

new TreeSet<test>(new test());

I agree. Here's the link:
subject: TreeSet & Comparator
It's not a secret anymore!