[英]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
? 被
<
使用完成int
或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;
因此,您的代码等效于
Foo.intValue() < foo;
. 。 This is deeper than you might think: your
Foo < foo
will throw a NullPointerException
if Foo
is null
. 这比您想象的要深:如果
Foo
为null
则您的Foo < foo
将抛出NullPointerException
。
According to JLS, 15.20.1 根据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.
数值比较运算符的每个操作数的类型必须是可转换(第5.1.8节)为原始数值类型的类型,否则会发生编译时错误。 Binary numeric promotion is performed on the operands (§5.6.2).
对操作数执行二进制数值提升(第5.6.2节)。
Further, 5.6.2 states that 此外,5.6.2指出
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. 这就解释了程序中发生的情况:在执行比较之前,将
Integer
对象取消装箱。
由于自动装箱和拆箱,它们将使用int
完成。
The Wrapper types for primitive types in java does automatic "type casting" ( or autoboxing / unboxing) from Object to compatible primitive type. Java中原始类型的Wrapper类型会自动将“类型转换”(或自动装箱/拆箱)从Object转换为兼容的原始类型。 so Integer will be converted to int before passing it to comparison operators or arithmetic operators like < , > , == , = , + and - etc.
因此,在将其传递给比较运算符或算术运算符(如<,>,==,=,+和-等)之前,会将Integer转换为int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.