I'm a little confused, are you trying to make your own set class? The reason TreeSet uses the compare/comparator is because in addition to getting rid of duplicates, TreeSet also keeps all of it's data sorted, as if you were calling Collections.sort() on your set after every single time you added an object. It uses the compare method, or the comparator to see how to sort the data
I would start out by finding out the requirements, or specifications, for the Set class you had to write. For example you don't know whether you need a particular feature of TreeSet or not. So you should find that out.
Jacob Sonia wrote:But i see that in TreeSet there is a comparable/comparator used to compare the elements, how do i take care of it.
There's optionally a Comparator. One ot the constructors to TreeSet allows you to pass in a Comparator object.
Now if you allow this you must use this comparator when you keep the TreeSet ordered, otherwise you're supposed to use the natural order of the objects stored in the TreeSet. The latter means you must assume the objects implement Comparable.
Jacob Sonia wrote:If i want to create exactly like a hashset, what should be my approach
Exact?
I took all the interfaces implemented by HashSet and then I defined a new class MySet promising to implement those interfaces. I then let Eclipse add all missing methods. I also added the expected constructors from HashSet.
When you've implemented all these constructor and methods the MySet class will work exactly like a HashSet. Of course it's best to start small. Start with the default constructor and the add and the contains methods. That will constitute a little mini-HashSet.
Post by:autobot
I'm not sure if I approve of this interruption. But this tiny ad checks out:
a bit of art, as a gift, the permaculture playing cards