0

I used a self-defined comparator to initialize treeset, making it a min-heap. It works fine to remove duplicates of small numbers such as 1, 2, 3. But when the numbers are large, duplicates remain in the treeset. Here's my code:

public class Test { 
    public static void main(String[] args) { 
            Set<Integer> treeset = new TreeSet<>(new MyComparator()); 
            Integer[] array = new Integer[args.length]; 
            for (int i = 0 ; i < args.length ; i ++ ) { 
                    array[i] = Integer.valueOf(args[i]); 
                    treeset.add(array[i]); 
            } 
            for (Integer i : treeset) { 
                    System.out.print(i + " "); 
            } 
    } 

    public static class MyComparator implements Comparator<Integer> { 
            @Override 
            public int compare(Integer i1, Integer i2) { 
                    if (i1 < i2) { 
                            return -1; 
                    } else if (i1 == i2) { 
                            return 0; 
                    } else { 
                            return 1; 
                    } 
            } 
    } 

}

If I do java Test -2147483647 -2147483647 1 1, I get -2147483647 -2147483647 1. It seems like something is wrong with my comparator. I tried to debug. When -2147483647 and -2147483647 are compared, instead of returning 0, the compare method returns 1. Could someone please tell me why? Thank you in advance!

2 Answers2

1

You are comparing instances of Integer with ==, but ==, applied to Objects, only compares if they are the same instance. In your case, i1 and i2 are two distinct instances despite having the same value.

Use the equals method to compare the content like in:

...
                } else if (i1,equals(i2)) { 
                        return 0; 
...

Why does it work with small numbers: small integers (-128 to 127 by default) are cached by the Integer class to avoid having to create a new Instance every time these are needed. Details: Integer.valueOf(int)

user85421
  • 28,957
  • 10
  • 64
  • 87
0

When you create an Integerusing valueOf() values from -128 to 127 are cached. This means for these range of values using the operator == for comparison will return true if both objects have the same integer value. For integer values less than -128 and greater than 127 that will not work, comparison will return false for objects having the same value. So use the equals() method for comparison instead of == if you want it to work correctly all the time.

Omoro
  • 972
  • 11
  • 22