Search code examples
javaarrayscomparisoninteger

comparing the values of two Integers


I want to compare the values of two arrays of type Integer. I get the wrong answer when I compare their exact values, and the correct answer when I compare them with Arrays.equals:

    Integer a[]=new Integer[2];
    Integer b[]=new Integer[2];
    a[0]=138;
    a[1]=0;
    b[0]=138;
    b[1]=0;
    boolean c;
    c=a[0]==b[0];//c is false
    c=Integer.valueOf(a[0])==Integer.valueOf(b[0]);//c is false
    c=Arrays.equals(a, b);//c is true

Solution

  • You're looking for intValue, not Integer.valueOf (though it's easy to see how you could get them confused!):

    c = a[0].intValue() == b[0].intValue();
    

    Java has primitive types (int, byte, double, etc.) and also reference types (objects) corresponding to them for those situations where you need an object. Your code doing a[0] = 138; is auto-boxing the primitive value 138 inside an Integer instance.

    intValue returns the primitive int contained by an Integer instance. Integer.valueOf is used for getting an Integer instance (from an int or a String — in your case, it'll use valueOf(int) by auto-un-boxing your Integer reference).

    You can also do this:

    c = (int)a[0] == (int)b[0];
    

    ...which will trigger auto-unboxing.

    More about boxing (including auto-boxing and unboxing) in the specification.