| Author |
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
|
|
|
TreeSet(Comparator)
|
"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
|
|
Hi 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
|
Santiago
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.
|
thanks
Harvinder
|
 |
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
|
|
Rekha, Could you please post the correct code. I was also trying to test the code you posted with the modifications suggested by the others. Thanks, Meera
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
meera, See what harvinder says! TreeSet constructor accepts Comparator (A class that implements Comparator). new TreeSet<test>(new test());
|
cmbhatt
|
 |
 |
|
|
subject: TreeSet & Comparator
|
|
|