-2

I am using an explicit comparator to allow duplicates values in TreeSet. While extracting exact lower value for given value using TreeSet.lower() method I am getting output same as given value (argument inside TreeSet.lower() method)

import java.util.*;
public class GFG {
    public static void main(String args[])
    {
        TreeSet<Integer> tree = new TreeSet<Integer>(new Comparator<Integer>(){
            @Override
            public int compare(Integer a, Integer b){
                if(a >= b){
                    return 1;
                }else{
                    return -1;
                }
            }
            
        });

        // Add elements to this TreeSet
        tree.add(9);
        tree.add(5);
        tree.add(8);
        tree.add(1);
        tree.add(11);
        tree.add(3);

        System.out.println(tree.lower(11));
    }
}

Here tree.lower(11) returning 11 instead of 9.

ram gopal
  • 3
  • 1
  • 3
    The `lower()` method most likely relies on the comparator, and expects it to obey the contract (meaning that the comparator returns "_a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second_"). Your comparator returns `1` for `11`, hence this is the value that is returned by lower. – maloomeister Oct 27 '21 at 14:30
  • 3
    Your comparator is not valid, so don't expect the tree set to work correctly. And no, you can't write a valid comparator that allows duplicates. – Sweeper Oct 27 '21 at 14:30
  • **tl;dr**: if your comparator never returns `0`, then it is wrong. – Joachim Sauer Oct 27 '21 at 14:41

1 Answers1

1

In the definition of lower you find strictly less than the given element. A comparator returns 1 for strictly less. Your comparator returns 1 also for equality. The TreeSet therefore sees equality as strictly less, hence - given your comparator - 11 is strictly less than 11.

As an alternative you may use a SortedList instead of a TreeSet if you want to store duplicates.

ngong
  • 754
  • 1
  • 8
  • 23
  • Returning 1 means the first argument is greater than the second parameter, so 11 > 11, but since the comparator is assumed to be valid, 11 > 11 implies 11 < 11, by using the rule `sgn(compare(x, y)) == -sgn(compare(y, x))`. I think that could explain why `lower` returns 11, but I might be reading too much into this. – Sweeper Oct 27 '21 at 14:59