Java Wrapper equality test

自闭症网瘾萝莉.ら 提交于 2019-12-17 15:33:10

问题


  public class WrapperTest {

    public static void main(String[] args) {

        Integer i = 100;
        Integer j = 100;

        if(i == j)
            System.out.println("same");
        else
            System.out.println("not same");
    }

   }

The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.


回答1:


In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):

private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Integer(i - 128);
    }
}

See also: http://www.owasp.org/index.php/Java_gotchas




回答2:


Basically Integers between -127 and 127 are 'cached' in such a way that when you use those numbers you always refer to the same number in memory, which is why your == works.

Any Integer outside of that range are not cached, thus the references are not the same.




回答3:


@tunaranch is correct. It is also the same issue as in this Python question. The gist is that Java keeps an object around for the integers from -128 to 127 (Python does -5 to 256) and returns the same object every time you ask for one. If you ask for an Integer outside of this fixed range, it'll give you a new object every time.

(Recall that == returns whether two objects are actually the same, while equals compares their contents.)

Edit: Here's the relevant paragraph from Section 5.1.7 of the Java Language Specification:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Note that this also describes what happens with other types.




回答4:


It's to do with equality and autoboxing: http://web.archive.org/web/20090220142800/http://davidflanagan.com/2004/02/equality-and-autoboxing.html




回答5:


Your code doesn't compile. This is what I get:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Type mismatch: cannot convert from int to Integer Type mismatch: cannot convert from int to Integer

at WrapperTest.main(WrapperTest.java:5)

Variables i and j are instances of Integer object. Don't compare instances of object using "==" operator, use "equals" method instead.

Greetings



来源:https://stackoverflow.com/questions/456575/java-wrapper-equality-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!