When they are Is java integer always = = when equals()?

See English answer > java: integer equals vs. = = 5

Integer x = 5;
Integer y = x + 1;
Integer z = y - 1;
x.equals(z)
true   (boolean)
x == z
true   (boolean)

Is this just an artifact of my IDE, or are Java integer objects guaranteed to point to the same integer when they have the same value? The latter guarantee will simplify some of the code I'm writing

Solution

may not. Under normal circumstances, you cannot rely on = = and integer instances when trying to compare values To do this, you must unpack them as ints or use equals

What you see in the example is that the JDK caches and reuses a limited number of integer instances (for integers representing - 128 to 127) From integer Valueof (int) start:

Now, your code uses boxing transformation instead of integer Valueof, while the boxing conversion uses integer Valueof's specification doesn't say, but it may be exactly what they do (in fact; for example, boxing conversions and integers. Valueof uses the same underlying mechanism and cache)

If you use different values, you can see that = = is unreliable for integer instances: (live copy)

Integer x = 524;    // <==== Changed
Integer y = x + 1;
Integer z = y - 1;
System.out.println("equals? " + x.equals(z));
System.out.println("==? " + (x == z));

Output (maybe I got it on ideone, but the document says again that integer can cache other values):

equals? true
==? false
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>