Why Java does not see that Integers are equal?

后端 未结 6 1797
野的像风
野的像风 2020-11-29 06:51

I have integers that are supposed to be equal (and I verify it by output). But in my if condition Java does not see these variables to have the same value.

6条回答
  •  情歌与酒
    2020-11-29 07:04

    The condition at

    pay[0]==point[0]
    

    expression, uses the equality operator == to compare a reference

    Integer pay[0]
    

    for equality with the a reference

    Integer point[0]
    

    In general, when primitive-type values (such as int, ...) are compared with == , the result is true if both values are identical. When references (such as Integer, String, ...) are compared with == , the result is true if both references refer to the same object in memory. To compare the actual contents (or state information) of objects for equality, a method must be invoked. Thus, with this

    Integer[] point = new Integer[2];
    

    expression you create a new object that has got new reference and assign it to point variable.

    For example:

    int a = 1;
    int b = 1;
    Integer c = 1;
    Integer d = 1;
    Integer e = new Integer(1);
    

    To compare a with b use:

    a == b
    

    because both of them are primitive-type values.

    To compare a with c use:

    a == c
    

    because of auto-boxing feature.

    for compare c with e use:

    c.equals(e)
    

    because of new reference in e variable.

    for compare c with d it is better and safe to use:

      c.equals(d)
    

    because of:

    As you know, the == operator, applied to wrapper objects, only tests whether the objects have identical memory locations. The following comparison would therefore probably fail:

    Integer a = 1000;
    Integer b = 1000;
    if (a == b) . . .
    

    However, a Java implementation may, if it chooses, wrap commonly occurring values into identical objects, and thus the comparison might succeed. This ambiguity is not what you want. The remedy is to call the equals method when comparing wrapper objects.

提交回复
热议问题