# SortedSet and my own Integer comparator

• 03-20-2011, 12:30 PM
trixter
SortedSet and my own Integer comparator
Hello,

This is my Integer comparator:

Code:

```class cmp implements Comparator         {                 public int compare(Object OA, Object OB)             {                         int A=(Integer)OA,B=(Integer)OB;                         if (distR[A]!=distR[B]) return (int) (distR[A]-distR[B]);                         return A-B;             }         }```
I need it here:

Code:

`SortedSet<Integer> S = new TreeSet<Integer>(new cmp());`
In C++ I've done it several times in a similiar way and everything worked fine.
Here, it compiles, but sometimes when I write for example:

Code:

```int x=700; S.add(x);```
x is not added to the SortedSet, although it's different to any other value in the set. Why? :confused:
• 03-20-2011, 12:35 PM
Fubarable
The API for TreeSet states:

Quote:

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.
I would not use Integer here but rather a wrapper object that overrides equals and has a Comparator or implements Comparable in a similar way.
• 03-20-2011, 02:23 PM
trixter
Quote:

Originally Posted by Fubarable
The API for TreeSet states:

I would not use Integer here but rather a wrapper object that overrides equals and has a Comparator or implements Comparable in a similar way.

Thank you for your answer. Yes, I know that way of doing that, I just prefer not to create new classes if not necessary.

However, I found my mistake :) distR was the array of doubles and the values often were different, but the difference was about 0.0001, so - after casting to int - it was 0. This is why SortedSet "thaught" it was equal.

The topic now can be closed.