2009-01-19 87 views
19
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"); 
    } 

    } 

上面的代码给same运行时的输出,但是如果我们的ij值更改为1000的输出变为not same。当我为SCJP做准备时,需要明白这一点。有人可以解释这种行为。谢谢。Java包装平等测试

+0

非常有趣的问题,我不知道Java的行为如此。我倾向于在任何时候都使用equals(),所以我很幸运地避免了这个问题。 – moffdub 2009-01-19 05:39:58

回答

19

在Java中,-128到127(含)之间的整数通常由相同的Integer对象实例表示。这是通过使用称为IntegerCache一个内部类的处理(包含在整数类的内部,并用于例如当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); 
    } 
} 

参见:http://www.owasp.org/index.php/Java_gotchas

5

@tunaranch是正确的。这也是与此Python question相同的问题。要点在于Java保留了一个从-128到127的整数对象(Python可以从-5到256),并且每次请求时都返回相同的对象。如果你在这个固定范围之外要求一个Integer,它会每次给你一个新的对象。

(回想一下,==返回两个对象是否实际上相同的,而equals比较它们的内容。)

编辑:这里的有关段落从Section 5.1.7Java 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.

请注意,这也描述了其他类型会发生什么。

6

基本上,-127到127之间的整数是这样“缓存”的,即当你使用这些数字时,你总是指向内存中的相同数字,这就是为什么你的==工作。

该范围之外的任何整数都不会被缓存,因此引用不一样。

0

你的代码不能编译。这就是我得到:

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) 

变量i和j是Integer对象的实例。不要使用“==”运算符比较对象的实例,而应使用“equals”方法。

问候

+0

我想你正在使用java 1.4..try它与Java 1.5 – Warrior 2009-01-19 10:16:21