Wrapper classes and generic clarifications in Java [duplicate]
Asked Answered
M

1

5

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();
    }
}
Misdoing answered 25/1, 2019 at 11:0 Comment(1)
The first one does and int to int comparison (after unboxing the first operand). The second one does Object comparison (with ==).Nahuatl
T
10
   System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
   System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: false

sumInteger() returns an Integer and sum() returns an int, so you are testing the the equality of an Integer with an int, which causes the Integer to be auto-unboxed, so you end up comparing an int with an int. Both ints now have the same value, hence 'true'.

sumInteger() returns an Integer, calling sumInteger() again returns an Integer. These two Integers are separately created objects, yet both hold the same internal value. When you use '=='' compare them it compares the references and seeing as how each object was created independently the references are not equal, hence 'false'. Had you wanted to test the value for equality you would have needed to use the .equals() method.

Teodor answered 25/1, 2019 at 11:4 Comment(2)
It might be worth pointing out that sumInteger(bigs) == sumInteger(bigs) is not guaranteed to yield false - that depends on the value returned from the method. Integers up to a certain value are cached, and in that range the reference comparison would be true.Nipple
(which is the reason for bc == ab being true)Nipple

© 2022 - 2024 — McMap. All rights reserved.