这个问题在这里已有答案:
在下面的代码中,行System.out.println(sumInteger(bigs) == sumInteger(bigs));
显示为false。但是当我们再次比较另一个Integer包装类System.out.println(bc == ab);
时,它返回true。为什么在第一种情况下包装类的比较为false而在第二种情况下为true?
import java.util.Arrays;
import java.util.List;
public class Arrays {
public void array1() {
List<Integer> bigs = Arrays.asList(100,200,300);
System.out.println(sumInteger(bigs) == sum(bigs)); // 1. Output: true
System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. Output: false
Integer ab = 10;
System.out.println(ab == 10); //3. Output: true
Integer bc = 10;
System.out.println(bc == ab); //4. Output: true
}
public static int sum (List<Integer> ints) {
int s = 0;
for (int n : ints) { s += n; }
return s;
}
public static Integer sumInteger(List<Integer> ints) {
Integer s = 0;
for (Integer n : ints) { s += n; }
return s;
}
public static void main(String[] args) {
Array tm = new Array();
tm.array1();
}
}
System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: false
sumInteger()返回一个Integer,sum()返回一个int,因此您正在测试Integer与int的相等性,这会导致Integer被自动取消装箱,因此您最终将int与int进行比较。两个整体现在都具有相同的值,因此“真实”。
sumInteger()返回一个Integer,再次调用sumInteger()返回一个Integer。这两个整数是单独创建的对象,但都保持相同的内部值。当您使用'==''比较它们时,它会比较引用并查看每个对象是如何独立创建的,引用不相等,因此为“false”。如果你想测试相等的值,你需要使用.equals()方法。