0
public static void main(String[] args) {
     int var = 128;
     Integer i = var;
     int j = var;
     LinkedList<Integer> ll = new LinkedList<>();
     ll.add(var);
     System.out.println(i==j);
     System.out.println(i==ll.peek()); 
 }
Output:
true
false

The values of variable var below number 128 though gives correct output as:

Output:
true
true

Please explain why comparison fails for peek() on values above 127?

  • 1
    You're not comparing an int to an Integer. You're comparing an Integer to another Integer. So you should use `equals` rather than `==` – khelwood Apr 11 '20 at 10:28
  • 1
    I think you should read [this](https://stackoverflow.com/questions/13098143/why-does-the-behavior-of-the-integer-constant-pool-change-at-127) question and you will get partial answer. – Michał Krzywański Apr 11 '20 at 10:42

3 Answers3

2

Do it as follows:

System.out.println(i.equals(ll.peek()));

Remember, == compares the references, not the content.

Check Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java? to understand why it returned true for a number less than 128.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

This is because of the Integer constant pool. Java maintains Integer pool from -128 to 127

private static class IntegerCache {
        static final int low = -128;
        static final int high;  //set to 127
}

So for values between -128 to 127, same reference would be returned from cache but for other values new Integer object would be created.

Vikas
  • 6,868
  • 4
  • 27
  • 41
0

the operator == checks for reference equality. Because Integer i is a Class type, as well as the returned value of ll.peak(), you should use the equals() method to compare them.

Alon Parag
  • 137
  • 1
  • 10