• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet & Comparator

 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet(Comparator)
 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. I got it..
Thanks Wouter,Santiago and Harvinder !!!
 
meera kanekal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meera,

See what harvinder says!

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

new TreeSet<test>(new test());
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic