自动包装时,Java为了提高性能,对于-128到127的值封装成对象后,会在内存中被重复使用。
代码的输出为
true
1641745
1641745
false
11077203
14576877
也即是说 x 和 y 的引用相同,而 x1,y1的引用不同。
package C01;
public class IntegerTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer x = 100;
Integer y = 100;
System.out.println(x==y);
System.out.println(System.identityHashCode(x));
System.out.println(System.identityHashCode(y));
Integer x1 = 200;
Integer y1 = 200;
System.out.println(x1==y1);
System.out.println(System.identityHashCode(x1));
System.out.println(System.identityHashCode(y1));
}
}
代码的输出为
true
1641745
1641745
false
11077203
14576877
也即是说 x 和 y 的引用相同,而 x1,y1的引用不同。
本文探讨了Java自动装箱过程中对-128到127范围内整数的缓存机制,通过实例展示了该机制如何使得这些特定范围内的Integer对象共享同一内存地址,从而提高性能。
7135

被折叠的 条评论
为什么被折叠?



