简体   繁体   English

Java Wrapper相等测试

[英]Java Wrapper equality test

  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 . 上面的代码在运行时给出same的输出,但是如果我们将ij的值更改为1000,则输出变为not same As I'm preparing for SCJP, need to get the concept behind this clear. 在我为SCJP做准备时,需要明确这个概念。 Can someone explain this behavior.Thanks. 有人可以解释这种行为。谢谢。

In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. 在Java中,-128和127(包括)之间的整数通常由相同的Integer对象实例表示。 This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used eg when Integer.valueOf() is called, or during autoboxing): 这是通过使用一个名为IntegerCache的内部类(包含在Integer类中,并在调用Integer.valueOf()时或在自动装箱期间使用)来处理的:

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 另见: http//www.owasp.org/index.php/Java_gotchas

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. 基本上-127和127之间的整数是“缓存”的,这样当你使用这些数字时,你总是在内存中引用相同的数字,这就是你的==有效的原因。

Any Integer outside of that range are not cached, thus the references are not the same. 超出该范围的任何整数都不会被缓存,因此引用不相同。

@tunaranch is correct. @tunaranch是对的。 It is also the same issue as in this Python question . 它也与此Python问题中的问题相同 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. 要点是Java为-128到127之间的整数保留一个对象(Python确实为-5到256),并且每次请求时都返回相同的对象。 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.) (回想一下, ==返回两个对象是否实际相同,而equals比较它们的内容。)

Edit : Here's the relevant paragraph from Section 5.1.7 of the Java Language Specification : 编辑 :这是Java语言规范的 5.1.7节中的相关段落:

If the value p being boxed is true , false , a byte , a char in the range \ to \ , 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. 如果被装箱的值ptruefalse ,一个byte ,范围为\\char ,或者介于-128和127之间的int或短号,则让r1r2为任意两个装箱转换的结果p。 It is always the case that r1 == r2 . 始终是r1 == r2的情况。

Note that this also describes what happens with other types. 请注意,这也描述了其他类型的情况。

这与平等和自动装箱有关: http ://web.archive.org/web/20090220142800/http://davidflanagan.com/2004/02/equality-and-autoboxing.html

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 线程“main”中的异常java.lang.Error:未解决的编译问题:类型不匹配:无法从int转换为Integer类型不匹配:无法从int转换为Integer

at WrapperTest.main(WrapperTest.java:5)

Variables i and j are instances of Integer object. 变量i和j是Integer对象的实例。 Don't compare instances of object using "==" operator, use "equals" method instead. 不要使用“==”运算符比较对象的实例,而是使用“equals”方法。

Greetings 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM