nano_nano
nano_nano

Reputation: 12523

Elements removed after execute Comparator in TreeSet

I have this peace of code:

final SortedSet<NisType> lAllNNisType = new TreeSet<NisType>(new NisTypeComparator());
lAllNisType.addAll(pAllNisType); // where pAllNisType is of type ArrayList<NisType>

thats my comparator class:

  private class NisTypeComparator implements Comparator<NisType> {

    @Override
    public int compare(NisType pNisType, NisType pNisType2) {
       if (pNisType.getPrio()>pNisType2.getPrio())
         return 1;
       else if (pNisType.getPrio()<pNisType2.getPrio())
         return -1;
       else
         return 0;
    }
  }

My ArrayList pAllNisType is filled with 6 different objects(based on the equals and hashCode method). Nevertheless after this line was executed:

lAllNisType.addAll(pAllNisType);

lAllNisType contains only 5 objects. There is one comparison that returns 0. And as a result of this one object was removed from lAllNisType.

I have no idear what happens here. The objects are different. If I do something like that:

final Set<NisType> lAllNisType = new HashSet<NisType>(pAllNisType);

lAllNisType has 6 elements.

Thanks for your help

Stefan

Upvotes: 0

Views: 588

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

Yes, this is behaving precisely as documented.

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface 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 sorted set 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 sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

If compare is returning 0, then two of your elements are deemed equal as far as the set is concerned, and only one of them can occur in the set. If you want to retain both objects, you'll need to make your comparator differentiate between them, e.g. through a secondary ordering.

Upvotes: 1

Related Questions