- 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分别指向的不同的对象
这样设计 是为了节约内存
所以不要过分依赖自动装箱和拆箱