public class IntegerUnder128 {
public static void main(String[] args) {
Integer a = 10;
Integer b = 10;
if(a==b){ //这里比较是用自动拆箱,那么如何证明a与b是堆里的两个不同对象
System.out.println("a == b");
System.out.println(a);
System.out.println(b);
}else{
System.out.println("他们不相等!");
}
}
}我觉得他们是建立了两个对象,但比较时是被自动拆箱的。
public static void main(String[] args) {
Integer a = 10;
Integer b = 10;
if(a==b){ //这里比较是用自动拆箱,那么如何证明a与b是堆里的两个不同对象
System.out.println("a == b");
System.out.println(a);
System.out.println(b);
}else{
System.out.println("他们不相等!");
}
}
}我觉得他们是建立了两个对象,但比较时是被自动拆箱的。
估计是和那个 string pool 差不多
是池化的。
我明显明白,
问题是:
a 与 b是两个不同的对象。
如果证明。可以输出他们的内存地址吗?
整数类型(Long,Integer,Short,Byte)都有相同处理(“池化”)。Character也有“池化”,不过不是-128~127,是0到127.
Integer b = 10;
</code>小于127 很明显 a,b引用指向的都是catch里面的同一个对象new Integer(10)
private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
可以试试 Integer a = new Integer(10);
Integer b = new Integer(10);
if(a==b){
//if(a.equals(b)){
System.out.println("a == b");
System.out.println(a);
System.out.println(b);
}else{
System.out.println("a != b");
}
以上就是两个对象
不过if(a==b)应该不拆箱
Integer b = 200;a>=b :true
a<=b :true
a!=b :true
1. Integer a = 10; Java在编译的时候是执行的这个操作:Integer a = Integer.valueOf(10);
2. Integer.valueOf(10) 10在-128到127之间,所以 Integer a = IntegerCache.cache[i + offset];Integer b = 10; 同上 即 Integer b = IntegerCache.cache[i + offset];结果很明显了。
Integer b = 10;
能用吗????? 放到IDE中试试。
1.
Integer a = new Integer(10);
Integer b = new Integer(10);
这时是新实例化了两个引用类型对象,他们是两个对象(两个NEW).
2.
int a=10;
int b=10;
int型的就是字面量,不是引用类型,一直就是一个对象呀。
3.
Integer a = Integer.valueOf(10);
Integer b = Integer.valueOf(10);
一个对象,都指向堆中的10。
没想到小于128会是true
用Eclipse的debug功能,我得到了如下的结论。
Integer a = 10;这里发生了auto-boxing,没什么疑问;
但是怎么装箱的呢?
step into得到以下代码:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
基本上猜也可以得到结论(我没有仔细去看high的定义),a和b都是引用同一个对象了;
能不能确定呢?让我们来看debug给出的显示
a Integer (id=18)
b Integer (id=18)
在我几次的debug过程中,id的值是有变化的,但是每次a和b的id都是相同的,我认为id就是对象的id,故a和b引用同一对象;
另外说说a == b的时候有没有auto-unboxing呢?
可以加上int c = a;
step into可以看到解箱代码:
public int intValue() {
return value;
}
而在执行a == b的计算的时候step into发现并未执行上述代码,可以确认,这里的==没有解箱,只是比较a和b是否引用同一对象,由上,得到true的结果。