Boxed Primitives and Equivalence

老子叫甜甜 提交于 2019-11-27 23:35:11
Peter Štibraný

Boxed values between -128 to 127 are cached. Boxing uses Integer.valueOf method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.

Quote from Java language specification:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

This is what is really happening:

Integer c = Integer.valueOf(5);
Integer d = Integer.valueOf(a.intValue() + b.intValue());

Java maintains a cache of Integer objects between -128 and 127. Compare with the following:

Integer a = 300;
Integer b = 200;
Integer c = 500;
Integer d = a + b;
System.out.println(c == d);

Which should print false.

Rahel Lüthy

It's because some of the (auto-boxed) Integers are cached, so you're actually comparing the same reference -- this post has more detailed examples and an explanation.

Caching happens outside of autoboxing too, consider this:

Integer a = 1;
Integer b = new Integer(1);
Integer c = Integer.valueOf(1);

System.out.println(a == b);
System.out.println(b == c);
System.out.println(c == a);

this will print:

false
false
true

So I guess that generally you want to stay away from '==' when comparing Objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!