Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

java - When using == for a primitive and a boxed value, is autoboxing done, or is unboxing done

The following code compiles (with Java 8):

Integer i1 = 1000;
int i2 = 1000;
boolean compared = (i1 == i2);

But what does it do?

Unbox i1:

boolean compared = (i1.intvalue() == i2);

or box i2:

boolean compared = (i1 == new Integer(i2));

So does it compare two Integer objects (by reference) or two int variables by value?

Note that for some numbers the reference comparison will yield the correct result because the Integer class maintains an internal cache of values between -128 to 127 (see also the comment by TheLostMind). This is why I used 1000 in my example and why I specifically ask about the unboxing/boxing and not about the result of the comparison.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is defined in the JLS #15.21.1:

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

And JLS #5.6.2:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion [...]

So to answer your question, the Integer is unboxed into an int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...