参见英文答案 >
How to properly compare two Integers in Java? 8个
在下面的代码中,行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 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 ints) {
int s = 0;
for (int n : ints) { s += n; }
return s;
}
public static Integer sumInteger(List ints) {
Integer s = 0;
for (Integer n : ints) { s += n; }
return s;
}
public static void main(String[] args) {
Array tm = new Array();
tm.array1();
}
}