code:
-----------------------------------------------------------------------------
JDK source:
-----------------------------------------------------------------------------
原来1.5的box和unboxing功能只是个面具,编译器最终还是用了原来1.4的规则进行实现,不过1.5的Integer增加了 public static Integer valueOf(int i)的函数,内部实现了对-128到127之间的Integer对象的缓存,其用意和Boolean.valueOf一样避免过多的创建对象。看来我们今后应该避免写出new Integer(××)的代码了,应该都用Integer.valueOf(××)的方式。同时还有个StringBuilder的细节指的我们注意,这是1.5引入功能等同于StringBuffer的新类,只不过StringBuilder不再考虑线程安全的情况,看来1.5还是有不少针对效率的小细节优化,值得我们注意甚至是对编码习惯的更正。
int value = 100;
Integer a = value;
Integer b = value;
System.out.println(a + "==" + b + " ? " + (a == b));
value = 300;
a = value;
b = value;
System.out.println(a + "==" + b + " ? " + (a == b));
-----------------------------------------------------------------------------
output:
100==100 ? true
300==300 ? false
-----------------------------------------------------------------------------
decompile code:
int value = 100;
Integer a = Integer.valueOf(value);
Integer b = Integer.valueOf(value);
System.out.println((new StringBuilder()).append(a).append("==").append(b).append(" ? ").append(a == b).toString());
value = 300;
a = Integer.valueOf(value);
b = Integer.valueOf(value);
System.out.println((new StringBuilder()).append(a).append("==").append(b).append(" ? ").append(a == b).toString());
-----------------------------------------------------------------------------
JDK source:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
-----------------------------------------------------------------------------
原来1.5的box和unboxing功能只是个面具,编译器最终还是用了原来1.4的规则进行实现,不过1.5的Integer增加了 public static Integer valueOf(int i)的函数,内部实现了对-128到127之间的Integer对象的缓存,其用意和Boolean.valueOf一样避免过多的创建对象。看来我们今后应该避免写出new Integer(××)的代码了,应该都用Integer.valueOf(××)的方式。同时还有个StringBuilder的细节指的我们注意,这是1.5引入功能等同于StringBuffer的新类,只不过StringBuilder不再考虑线程安全的情况,看来1.5还是有不少针对效率的小细节优化,值得我们注意甚至是对编码习惯的更正。