javacollectionstreeset

TreeSet.lower() Method is not returning required output while using explicit comparator constructor


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.


Solution

  • 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.