JAVA非常见知识

142 阅读1分钟

Integer缓存问题

  • 内容
在 -128127 (闭区间)之间的 int 类型的值 
boolean 类型的 true 或 false
范围在’\u0000’和’\u007f’ (闭区间)之间的 char 类型的数值 p
自动包装成 ab 两个对象时, 可以使用 a == b 判断 ab 的值是否相等。
  • Unicode编码表 0000-007F:C0控制符及基本拉丁文 (C0 Control and Basic Latin)
    包含大小写字母和数字

image.png

  • Ineger.valueOf
// Integer a = 1; 这种声明式的会调用valueOf创建对象(javap or 断点)
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
// 可以修改high,low不可改
// -Djava.lang.Integer.IntegerCache.high=<value>
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
           // ...
    }
}
// Long不可修改
private static class LongCache {
    private LongCache(){}

    static final Long cache[] = new Long[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Long(i - 128);
    }
}
  • 为什么 如果想减少内存占用,提高程序运行的效率,可以将常用的对象提前缓存起来,需要时直接从缓存中提取。