八股文——JAVA基础:包装类型的缓存机制了解么?

对于包装类中的整形包装类,Byte、Short、Integer、Long等,对于数值在-128到127的内容会在堆中创建缓存,比如拿Integer举例,Integer a = 10,Integer b =10,

10对应在缓存数组CACHE[138],所以a == b是比较的就是CACHE[138]对应的地址,显然两者地址是相同的。对应源码如下

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static {
        // high value may be configured by property
        int h = 127;
    }
}

你可能感兴趣的:(java,开发语言)