栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Interger常量池,常量池上限调整

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Interger常量池,常量池上限调整

原理

Integer包装类有默认缓存池,范围是【 -128~127】 。
其他基本数据类型的包装类都有这个缓存池,包括:Byte,Short,Long。Float和Double没有

 
public Integer(int value) {
    this.value = value;
}
 
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        eturn value == ((Integer)obj).intValue();
    }
    return false;
}

public int intValue() {
    return value;
}

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
        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) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // 最大的 数组 size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            }
            high = h;
            ache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
    }
    private IntegerCache() {}
}        
  1. Integer有一个实例域value,它保存了这个Integer所代表的int型的值,且它是final的,也就是说这个Integer对象一经构造完成,它所代表的值就不能再被改变。
  2. Integer重写了equals()方法,它通过比较两个Integer对象的value,来判断是否相等。
  3. 重点是静态内部类IntegerCache,通过类名就可以发现:它是用来缓存数据的。它有一个数组,里面保存的是连续的Integer对象。
  4. low:代表缓存数据中最小的值,固定是-128。
  5. high:代表缓存数据中最大的值,它可以被该改变,默认是127。high最小是127,最大是Integer.MAXVALUE-(-low)-1,如果high超过了这个值,那么cache[ ]的长度就超过Integer.MAXVALUE了,也就溢出了。
  6. cache[]:里面保存着从[low,high]所对应的Integer对象,长度是high-low+1(因为有元素0,所以要加1)。
  7. 调用valueOf(int i)方法时,首先判断i是否在[low,high]之间,如果是,则复用Integer.cache[i-low]。比如,如果Integer.valueOf(3),直接返回Integer.cache[131];如果i不在这个范围,则调用构造方法,构造出一个新的Integer对象。
  8. 调用intValue(),直接返回value的值。通过3和4可以发现,默认情况下,在使用自动装箱时,VM会复用[-128,127]之间的Integer对象。
java中整数常量池(-128~127)上限如何调整?

java中Integer有一个常量池范围-128~127

如果我想让 下面也返回true,该怎么做?
Integer a = 500, b = 500;
System.out.println(a == b);

答案就在java.lang.Integer.IntegerCache 这个类的源码上


    private static class IntegerCache {
       // ...
    }
-XX:AutoBoxCacheMax=
-Djava.lang.Integer.IntegerCache.high=

这2个参数都可以控制上限。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/591838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号