在下面的代码中,该行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();
}
}
Run Code Online (Sandbox Code Playgroud)
System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: false
Run Code Online (Sandbox Code Playgroud)
sumInteger()返回一个Integer,sum()返回一个int,因此您正在测试一个与int的Integer的相等性,这会导致将Integer自动拆箱,因此最终将一个int与一个int进行比较。现在两个int具有相同的值,因此为'true'。
sumInteger()返回一个Integer,再次调用sumInteger()将返回一个Integer。这两个Integer是分别创建的对象,但是都具有相同的内部值。当您使用'=='比较它们时,它将比较引用,并看到每个对象是如何独立创建的,因此引用不相等,因此为'false'。如果您想测试值的相等性,则需要使用.equals()方法。
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |