详解Java 虚拟机(第④篇)——8 种基本类型的包装类和常量池

发布时间:2020-08-08 10:32:22 作者:无敌天骄
来源:ITPUB博客 阅读:150

详解Java 虚拟机(第④篇)——8 种基本类型的包装类和常量池

Integer 的部分源码:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

在 Java 8 中,Integer 缓存池的大小默认为 -128~127。

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;
}

示例1:

Integer i1=40;
//Java 在编译的时候会直接将代码封装成 Integer i1=Integer.valueOf(40);从而使用常量池中的对象。
Integer i2 = new Integer(40);
//创建新的对象。
System.out.println(i1==i2);//输出false

示例2:Integer有自动拆装箱功能

Integer i1 = 40;
Integer i2 = 40;
Integer i3 = 0;
Integer i4 = new Integer(40);
Integer i5 = new Integer(40);
Integer i6 = new Integer(0);
System.out.println("i1=i2   " + (i1 == i2)); //输出 i1=i2  true
System.out.println("i1=i2+i3   " + (i1 == i2 + i3)); //输出 i1=i2+i3  true
//i2+i3得到40,比较的是数值
System.out.println("i1=i4   " + (i1 == i4)); //输出 i1=i4 false
System.out.println("i4=i5   " + (i4 == i5)); //输出 i4=i5 false
//i5+i6得到40,比较的是数值
System.out.println("i4=i5+i6   " + (i4 == i5 + i6)); //输出 i4=i5+i6 true
System.out.println("40=i5+i6   " + (40 == i5 + i6)); //输出 40=i5+i6 true
推荐阅读:
  1. Java常量池的介绍和使用
  2. java内存分配分析/栈内存、堆内存

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 包装 常量

上一篇:Check connection related issue of mysql

下一篇:MySQL 5.5 常用的复制环境管理命令

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》