在下面的代码中,System.out.println(sumInteger(bigs) == sumInteger(bigs));行显示为false。但是,当我们再次比较另一个Integer包装类System.out.println(bc == ab);时,它返回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();
}
}发布于 2019-01-25 11:04:51
System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: falsesumInteger()返回一个整数,sum()返回一个int,因此您正在测试int与int的相等性,这将导致Integer被自动取消装箱,因此您将一个int和一个int进行比较。这两个ints现在具有相同的值,因此“true”。
sumInteger()返回一个整数,调用sumInteger()再次返回一个整数。这两个整数是单独创建的对象,但都持有相同的内部值。当您使用‘==’比较它们时,它会比较引用并查看每个对象是如何独立创建的--引用是不相等的,因此是'false‘。如果您想测试相等的值,则需要使用.equals()方法。
https://stackoverflow.com/questions/54363952
复制相似问题