How != and == operators work on Integers in Java? [duplicate]

徘徊边缘 提交于 2019-11-26 15:29:37

Integers are cached for values between -128 and 127 so Integer i = 127 will always return the same reference. Integer j = 128 will not necessarily do so. You will then need to use equals to test for equality of the underlying int.

This is part of the Java Language Specification:

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

But 2 calls to Integer j = 128 might return the same reference (not guaranteed):

Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Because small integers are interned in Java, and you tried the numbers on different sides of the "smallness" limit.

There exist an Integer object cache from -128 and up to 127 by default. The upper border can be configured. The upper cache border can be controlled by VM option -XX:AutoBoxCacheMax=<size>

You are using this cache when you use the form:

 Integer i1 = 127;

or

Integer i1 = Integer.valueOf(127);

But when you use

Integer i1 = new Integer(127);

then you're guaranteed to get a new uncached object. In the latter case both versions print out the same results. Using the cached versions they may differ.

https://www.owasp.org/index.php/Java_gotchas

I got this link from one of my professors, pretty informative.

Java caches integers from -128 to 127 That is why the objects ARE the same.

I think the == and != operators when dealing with primitives will work how you're currently using them, but with objects (Integer vs. int) you'll want to perform testing with .equals() method.

I'm not certain on this, but with objects the == will test if one object is the same object or not, while .equals() will perform testing that those two objects contain equivalence in value (or the method will need to be created/overridden) for custom objects.

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