日期:2014-05-20  浏览次数:20628 次

关于int和integer的一个简单问题,也是网上看见的,但是没想明白
Java code

public class test2 {

    public static void main(String[] args) {
        int i = 127;
        Integer s = i;
        Integer s1= i;
        System.out.println(s==s1);
    }
}



输出 true。

Java code

public class test2 {

    public static void main(String[] args) {
        int i = 128;
        Integer s = i;
        Integer s1= i;
        System.out.println(s==s1);
    }
}



输出 false

------解决方案--------------------
http://www.ticmy.com/?p=110
------解决方案--------------------
对于Integer integer = ?

java在自动装箱时,对于值是-128-127会封装成一个Integer对象在内存中可以重用,类似 通过String s = "xx"创建的字符串可重用,所以s和s1指向的是同一个对象

但是超过-128-127,被封装的对象并不能被重用,所以s和s1分别指向的不同的对象

这样设计 是为了节约内存

所以不要过分依赖自动装箱和拆箱