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?

2
  • 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 == Commented Apr 11, 2020 at 10:28
  • 1
    I think you should read this question and you will get partial answer. Commented Apr 11, 2020 at 10:42

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

how come == works at all if it is comparing the references?
@JunisvaultCo - do you mean how i==j returns true? If yes, that is because of Autoboxing and Unboxing.
he stated that i==ll.peek() returns true for var<128. And indeed, I've tested it with 127 andi t does. Why? It is comparing references.
@JunisvaultCo have a look at this
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.