Integer对象的深入理解~

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013591740/article/details/53215003

一段有趣的代码~

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类也有类似的内部类,具体请详看源码

猜你喜欢

转载自blog.csdn.net/u013591740/article/details/53215003