1

I couldn't understand why it's printing false when HashMap key is 2

Map<Integer, Integer> first = new HashMap<Integer, Integer>();

Map<Integer, Integer> second = new HashMap<Integer, Integer>();

first.put(1, 10);
second.put(1, 10);

first.put(2, 155);
second.put(2, 155);

for (int i = 1; i <= 2; i++) {
    System.out.print("first=" + first.get(i) + "," + "second="
            + second.get(i) + " ");
    System.out.println(first.get(i) == second.get(i));

}

Result

first=10,second=10 true
first=155,second=155 false
friendlyBug
  • 518
  • 5
  • 12
  • 1
    An instance of `Integer` for values between `-128` and `127` is cached. So the values `10` are the exact same instance. That's not the case for `155`. – Paul Boddington Apr 11 '15 at 17:49
  • Possible duplicate of [Why does 128==128 return false but 127==127 return true in this code?](http://stackoverflow.com/questions/1700081/why-does-128-128-return-false-but-127-127-return-true-in-this-code) – Tom Oct 06 '15 at 10:59

2 Answers2

3

In this line:

System.out.println(first.get(i) == second.get(i));

no unboxing takes place.

Both sides of the == operator are Object instances; therefore, what will be performed is an object reference equality.

The first case, with 10, only works "by luck".

Basically, what happens is that when you:

first.put(1, 10);

what is really called, because of boxing, is:

first.put(Integer.valueOf(1), Integer.valueOf(10));

Now, it so happens that the Integer class has an inline cache which covers all values from -128 up to 127 at least, as the javadoc of Integer.valueOf() explains:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

But 155 is greater than 127; which means that this method is not required to cache it, in which case a new Integer instance will be created. And this is what happens here.

fge
  • 119,121
  • 33
  • 254
  • 329
0

That's what JLS 15.21.3 told you about your behavior:

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

St.Antario
  • 26,175
  • 41
  • 130
  • 318