我知道如果你比较一个装箱的原语Integer和一个常量,比如:
Integer a = 4;
if (a < 5)
A将自动被打开,比较将会起作用。
但是,当您比较两个带框的整数并希望比较相等或小于/大于时会发生什么?
Integer a = 4;
Integer b = 5;
if (a == b)
上面的代码是否会检查它们是否是同一个对象,或者在这种情况下它会自动开箱吗?
是什么:
Integer a = 4;
Integer b = 5;
if (a < b)
?
我知道如果你比较一个装箱的原语Integer和一个常量,比如:
Integer a = 4;
if (a < 5)
A将自动被打开,比较将会起作用。
但是,当您比较两个带框的整数并希望比较相等或小于/大于时会发生什么?
Integer a = 4;
Integer b = 5;
if (a == b)
上面的代码是否会检查它们是否是同一个对象,或者在这种情况下它会自动开箱吗?
是什么:
Integer a = 4;
Integer b = 5;
if (a < b)
?
当前回答
从Java 1.7开始,你可以使用Objects.equals:
java.util.Objects.equals(oneInteger, anotherInteger);
如果参数相等则返回true,如果参数为false则返回false 否则。因此,如果两个参数都为空,则返回true 如果恰好有一个参数为null,则返回false。否则, 等号是用第一个的等号法来确定的 论点。
其他回答
我们应该总是使用equals()方法来比较两个整数。这是推荐的做法。
如果我们使用==比较两个整数,由于JVM的内部优化,这将适用于一定范围的整数值(从-128到127的整数值)。
请看例子:
案例1:
Integer a = 100;
Integer b = 100;
if (a == b) {
System.out.println("a and b are equal");
} else {
System.out.println("a and b are not equal");
}
在上述情况下,JVM从缓存池中使用a和b的值,并返回相同的对象实例(因此内存地址)的整数对象,我们得到两者相等。它是JVM为特定范围值所做的优化。
情况2:在这种情况下,a和b不相等,因为它没有从-128到127的范围。
Integer a = 220;
Integer b = 220;
if (a == b) {
System.out.println("a and b are equal");
} else {
System.out.println("a and b are not equal");
}
正确的方法:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
==仍然测试对象是否相等。然而,这很容易被愚弄:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false
你使用不等式的例子是可以工作的,因为它们不是在对象上定义的。但是,使用==比较时,仍然会检查对象是否相等。在这种情况下,当你从一个盒装的原语中初始化对象时,使用了相同的对象(对于a和b)。这是一个不错的优化,因为原语盒类是不可变的。
==检查引用是否相等,但是当编写如下代码时:
Integer a = 1;
Integer b = 1;
Java足够聪明,可以为a和b重用相同的不可变变量,所以这是正确的:a == b。好奇的是,我写了一个小例子来说明Java停止以这种方式优化的地方:
public class BoxingLol {
public static void main(String[] args) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Integer a = i;
Integer b = i;
if (a != b) {
System.out.println("Done: " + i);
System.exit(0);
}
}
System.out.println("Done, all values equal");
}
}
当我编译和运行这个(在我的机器上),我得到:
Done: 128
这个方法用空检查比较两个Integer。请参阅测试。
public static boolean compare(Integer int1, Integer int2) {
if(int1!=null) {
return int1.equals(int2);
} else {
return int2==null;
}
//inline version:
//return (int1!=null) ? int1.equals(int2) : int2==null;
}
//results:
System.out.println(compare(1,1)); //true
System.out.println(compare(0,1)); //false
System.out.println(compare(1,0)); //false
System.out.println(compare(null,0)); //false
System.out.println(compare(0,null)); //false
System.out.println(compare(null,null)); //true
从Java 1.7开始,你可以使用Objects.equals:
java.util.Objects.equals(oneInteger, anotherInteger);
如果参数相等则返回true,如果参数为false则返回false 否则。因此,如果两个参数都为空,则返回true 如果恰好有一个参数为null,则返回false。否则, 等号是用第一个的等号法来确定的 论点。