Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper classes and generic clarifications in Java [duplicate]

Tags:

java

boxing

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();
    }
}
like image 650
Shalin Fernando Avatar asked Jan 25 '19 11:01

Shalin Fernando


1 Answers

   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.

like image 56
Dumidu Udayanga Avatar answered Sep 22 '22 05:09

Dumidu Udayanga