Java教程

研读源码很重要

本文主要是介绍研读源码很重要,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

今天碰巧遇到个问题

 

 研读了源码后,发现,Integer类中有个内部类,

用100定义两个包装类型的变量a,b后,包装类型用==比较的是对象的内存地址,

IntegerCache,这个类对-127到128范围内的数字做了缓存,也就是说这范围内的数字的内存地址是一样的,
所以返回true
超出这个范围后,相同的值1000,定义两遍Integer类型的对象后,这俩对象的内存地址就是不同的,所以返回false

/**
 * Cache to support the object identity semantics of autoboxing for values between
 * -128 and 127 (inclusive) as required by JLS.
 *
 * The cache is initialized on first usage.  The size of the cache
 * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
 * During VM initialization, java.lang.Integer.IntegerCache.high property
 * may be set and saved in the private system properties in the
 * sun.misc.VM class.
 */

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low));
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}
这篇关于研读源码很重要的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!