Forums Register Login

TreeSet & Comparator

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Yes. I got it..
Thanks Wouter,Santiago and Harvinder !!!
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
meera,

See what harvinder says!

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

new TreeSet<test>(new test());
We're all out of roofs. But we still have tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 5627 times.
Similar Threads
Inquisition Question
Comparator
Comparator and Compatable Query
Comparable or Comparator
comparator comparable
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:19:45.