转自:http://blog.csdn.net/randyjiawenjie/article/details/7603427
Integer.valueOf()方法实现如下:
- 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);
- }
Integer.valueOf()方法基于减少对象创建次数和节省内存的考虑,缓存了[-128,127]之间的数字。此数字范围内传参则直接返回缓存中的对象。在此之外,直接new出来。
IntegerCache的实现:
- private static class IntegerCache {
- 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);
- }
- }
测试代码
- Integer i1 = Integer.valueOf(12);
- Integer i2 = Integer.valueOf(12);
- Integer i3 = Integer.valueOf(129);
- Integer i4 = Integer.valueOf(129);
- System.out.println(i1==i2);
- System.out.println(i3==i4);
- System.out.println(i1.equals(i2));
- System.out.println(i3.equals(i4));
打印结果如下:
true
false
true
true