In the below code, the line System.out.println(sumInteger(bigs) == sumInteger(bigs));
displays as false. But when again we compare the another Integer wrapper classes System.out.println(bc == ab);
, it returns true. Why is the comparison of wrapper classes false in the first case and true in the second case?
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
toint
comparison (after unboxing the first operand). The second one doesObject
comparison (with==
). – Nahuatl