【发布时间】:2019-06-19 05:02:43
【问题描述】:
在下面的代码中,System.out.println(sumInteger(bigs) == sumInteger(bigs)); 行显示为 false。但是当我们再次比较另一个整数包装类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();
}
}
【问题讨论】:
-
第一个做和
int到int的比较(在拆箱第一个操作数之后)。第二个进行Object比较(与==)。