Integer对象深入了解
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { Class cache = Integer.class.getDeclaredClasses()[0]; // 1 Field myCache = cache.getDeclaredField("cache"); // 2 myCache.setAccessible(true);// 3 Integer[] newCache = (Integer[]) myCache.get(cache); // 4 newCache[132] = newCache[134]; // 5 int a = 2; int b = a + a; Integer c = 4; System.out.printf("%d + %d = %d", a, a, b); // System.out.println(); System.out.println("c ==> " + c); System.out.println(a + " + " + a + " = " + b); }运行结果:
主要原因:Integer类的内部类IntegerCache.java,对-128到127提供了缓存作用,Character类也有类似的内部类,具体请详看源码