views:

157

answers:

3

I used a TreeSet with a self written Comparator. Now when I'm adding elements to the TreeSet and the Comparator's compare methods returns 0, it seems like the TreeSet contains only one of the Object with equal ranking.

I didn't see that this behaviour is documented in the javadocs. Maybe I miss something. Can you confirm this behaviour?

I edited the Comparator. Now it never returns 0 and the TreeSet contains all the Objects with equal ranking.

Is that the way it has to be, if I want to have multiple Objects with equal ranking?

+5  A: 

That's the way it has to be, as a set is defined as including equal objects only once.

When your Comparator returns 0, two objects are considered equal, therefore only one (probably the first) of all equal objects is included in the set.

mrueg
+6  A: 

Yes, this is documented in the JavaDoc for TreeSet:

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. (Emphasis mine)

Simon Nickerson
A: 

If you want a sorted collection that can hold multiple objects which are equal to each other, then the TreeMultiset from Google Collections would probably do the trick.

gustafc