简体   繁体   中英

Comparing an int and Integer in Java

Consider the following snippet:

Integer Foo = 2;
int foo = 1;
boolean b = Foo < foo;

is < done using int or Integer ? What about == ?

For all the relational operators (including therefore < and == ), if one type is the boxed analogue of the other, then the boxed type is converted to the unboxed form.

So your code is equivalent to Foo.intValue() < foo; . This is deeper than you might think: your Foo < foo will throw a NullPointerException if Foo is null .

According to JLS, 15.20.1

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2).

Further, 5.6.2 states that

If any operand is of a reference type, it is subjected to unboxing conversion

This explains what is happening in your program: the Integer object is unboxed before the comparison is performed.

由于自动装箱和拆箱,它们将使用int完成。

The Wrapper types for primitive types in java does automatic "type casting" ( or autoboxing / unboxing) from Object to compatible primitive type. so Integer will be converted to int before passing it to comparison operators or arithmetic operators like < , > , == , = , + and - etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM