比较整数对象 [英] Comparing Integer objects
问题描述
我有以下代码:
public class Test {
public static void main(String[] args) {
Integer alpha = new Integer(1);
Integer foo = new Integer(1);
if(alpha == foo) {
System.out.println("1. true");
}
if(alpha.equals(foo)) {
System.out.println("2. true");
}
}
}
输出如下:
2. true
但是更改整数对象的类型
to int
将产生不同的输出,例如:
However changing the type of an Integer object
to int
will produce a different output, for example:
public class Test {
public static void main(String[] args) {
Integer alpha = new Integer(1);
int foo = 1;
if(alpha == foo) {
System.out.println("1. true");
}
if(alpha.equals(foo)) {
System.out.println("2. true");
}
}
}
新输出:
1. true
2. true
怎么会这样?为什么第一个示例代码输出 1。 true
?
How can this be so? Why doesn't the first example code output 1. true
?
推荐答案
对于参考类型, ==
检查引用是否相等,即它们是否指向同一个对象。
For reference types, ==
checks whether the references are equal, i.e. whether they point to the same object.
对于基本类型, ==
检查值是否相等。
For primitive types, ==
checks whether the values are equal.
java.lang.Integer
是一种引用类型。 int
是一种基本类型。
java.lang.Integer
is a reference type. int
is a primitive type.
编辑:如果一个操作数是基本类型,另一个是参考打开到合适的基本类型的类型, ==
将比较值,而不是引用。
If one operand is of primitive type, and the other of a reference type that unboxes to a suitable primitive type, ==
will compare values, not references.
这篇关于比较整数对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!