posted 18 years ago
From the specification of TreeSet it is given as
"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 key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. "
From the above paragraph, it is clear that TreeSet is using compareTo() function for checking whether two instances are the same. Here we are providing function for compareTo() , and that function returns zero, when we try to add the second instance of TestComparable. So the second object is not added to the TreeSet.
But in the case of HashSet, hashCode() and equals() will be invoked. Since we are not overriding those functions, equals returns false and the second object is added to the HashSet.