1

The code results this output --> [5, 4, 3], Why 4 is still in the set ?

public class Temp4 {
    public static void main (String[] args)   { 
        TreeSet<Integer> set = new TreeSet<Integer>( (I1,I2)->(I1 < I2) ? 1 : (I1 > I2) ? -1 :-1);

        set.add(new Integer(5) );
        set.add(new Integer(3) );              
        set.add(new Integer(4) );

        set.remove(new Integer(4)) ;

        System.out.println( set  );

    }
}
  • 5
    Your comparator is wrong. It should return 0 as default value. As is, no equality can found using your comparator. – amanin Apr 08 '20 at 10:30

2 Answers2

2

First of all, your Comparator is broken, it should return 0 for equal elements.

Second the TreeSet uses compare to find elements, in contradiction to the general Set contract.

See here

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.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
0

The problem is your comparator, you're not handling the cases in which the objects are equal (you should return 0). Anyway, in your case you don't even need to explicitly use a custom comparator, you can create your set like this and it will work:

TreeSet<Integer> set= new TreeSet<Integer>(Collections.reverseOrder()) ;
robertobatts
  • 965
  • 11
  • 22