Search code examples
javalinked-listintinteger

Comparison of int to Integer not working after adding to Linkedlist


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?


Solution

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