public class test2 { public static void main(String[] args) {
int i = 127;
Integer s = i;
Integer s1= i;
System.out.println(s==s1);
}
}
输出 true。
public class test2 { public static void main(String[] args) {
int i = 128;
Integer s = i;
Integer s1= i;
System.out.println(s==s1);
}
}
输出 false

解决方案 »

  1.   

    代码等价于public class test2 {    public static void main(String[] args) {
            int i = 127;
            Integer s = Integer.valueOf(i);
            Integer s1= Integer.valueOf(i);
            System.out.println(s==s1);
        }
    }
    然后看下Integer.valueOf(int)的源码,你jdk会发现有缓存对象。
      

  2.   

    http://www.ticmy.com/?p=110
      

  3.   

    对于Integer integer = ?java在自动装箱时,对于值是-128-127会封装成一个Integer对象在内存中可以重用,类似 通过String s = "xx"创建的字符串可重用,所以s和s1指向的是同一个对象但是超过-128-127,被封装的对象并不能被重用,所以s和s1分别指向的不同的对象这样设计 是为了节约内存所以不要过分依赖自动装箱和拆箱
      

  4.   

    Integer内部缓存了[-128,127]之间的Integer对象。