Treeset orders the elements that are inserted into it. if an Integer or String element si inserted, I can understand the ordering, but if we are going to insert some Objects of an User defined class, will it get sorted and if it so, o what basis, it gets sorted?
Thanks for the reply. I have gone through them and then came here to clear it. Any brief explanation would clear the air is what my expectation was...
John de Michele
Joined: Mar 09, 2009
Ok, here's the relevant part of the TreeSet javadoc:
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Generally, if you want a class to usable in a way that has some ordering, you'll need to implement the Comparable or the Comparator interfaces. In addition, overriding the equals() and hashCode() methods is just about a requirement for a well-behaved class in this situation.
The TreeSet can be configured with a Comparator. That is a special class you define that tells the TreeSet how its elements should be sorted. If no Comparator is given, then the TreeSet will sort things according to the "natural order" of the elements. What does that mean? Certain classes implement an interface called Comparable. The Integer class from your example is Comparable so the TreeSet knows how to sort them, and in fact all number classes and Strings are also Comparable. Other classes don't implement Comparable and so the TreeSet can't sort them without a custom Comparator.
If you create a class, and you want its instances to be sorted correctly in a TreeSet, you can simply make it implement Comparable and then write a compareTo() method that explains how they should be sorted. It's actually very easy to do!