基本数据类型缓存池
-
基本数据类型的包装类除了 Float 和 Double 之外,其他六个包装器类(Byte、Short、Integer、Long、Character、Boolean)都有常量缓存池。
-
Byte:-128~127,也就是所有的 byte 值
-
Short:-128~127
-
Long:-128~127
-
Character:\u0000 - \u007F
-
Boolean:true 和 false
-
Integer:-128~127
-
public static void main(String[] args) { // 每次都会新建一个对象 Integer a = new Integer(11); Integer b = new Integer(11); // false System.out.println(a == b); // 使⽤用缓存池中的对象,多次调用只会取同⼀一个对象的引用 Integer c = Integer.valueOf(11); Integer d = Integer.valueOf(11); // true System.out.println(c == d); // 128超出Integer的常量池范围-128~127 Integer e = Integer.valueOf(128); Integer f = Integer.valueOf(128); // false System.out.println(e == f); }
- 如果使用
new Integer()
创建对象,即使值在 -128 到 127 范围内,也不会被缓存,每次都会创建新的对象。因此,推荐使用Integer.valueOf()
方法获取整数对象。 - Integer源码
public static Integer valueOf(int i) { // 检查该整数是否在 IntegerCache 中,如果在,则返回缓存中的对象 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 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) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; // 往缓冲池填数据备用 for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }
- JVM 启动的时候,通过
-XX:AutoBoxCacheMax=NNN
来设置缓存池的大小,最大到Integer.MAX_VALUE -129
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/18301341
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步