public class Test2 {
public void t1() {
Integer i = 2;
Integer j = 2;
System.out.print("t1:");
System.out.println(i == j);
}

public void t2() {
Integer i = 127;
Integer j = 127;
System.out.print("t2:");
System.out.println(i == j);
}
public void t3() {
Integer i = 128;
Integer j = 128;
System.out.print("t3:");
System.out.println(i == j);
}
public void t4() {
Integer i = -2;
Integer j = -2;
System.out.print("t4:");
System.out.println(i == j);
}
public void t5() {
Integer i = -128;
Integer j = -128;
System.out.print("t5:");
System.out.println(i == j);
}
public void t6() {
Integer i = -129;
Integer j = -129;
System.out.print("t6:");
System.out.println(i == j);
}

public static void main(String[] args) {
Test2 test = new Test2();
test.t1();
test.t2();
test.t3();
test.t4();
test.t5();
test.t6();
}
}
JDK1.6运行结果:
t1:true
t2:true
t3:false
t4:true
t5:true
t6:false
问下为什么有两个false;

解决方案 »

  1.   

    跟autobox的实现有关    public static Integer valueOf(int i) {
            if(i >= -128 && i <= IntegerCache.high)
                return IntegerCache.cache[i + 128];
            else
                return new Integer(i);
        }
    -128,-129是返回一个new Integer
      

  2.   

    Integer是一个immutable class,但是状态上亿种,不可能用静态实例缓存所有状态。不过,SUN的工程师还是作了一点优化,Integer类缓存了-128到127这256个状态的Integer,如果使用Integer.valueOf(int i),传入的int范围正好在此内,就返回静态实例.
      

  3.   

    boolean,byte,char<=127,位于-128到127之间的short,int,这些数据自动装箱时,会被包装到固定的对象中。也就是说Interger a=10; 和 Integer b=10;是同一个对象。就好比String s1="hello"; 和String s2="hello"一样。