Java中关于Integer的使用

首先,我们先来看一下下面的代码:

ini 复制代码
Integer a = 20;
Integer b = 20;
System.out.println(a == b);

Integer c = 128;
Integer d = 128;
System.out.println(c == d);

小伙伴们能否一眼看出结果?然后用idea运行看看,跟自己想的结果是否一样?

今天我们就来说说java中Integer的使用问题。 下面先贴出运行结果:

至于为什么会出现以上的结果呢?我们先来看看"=="操作符,对于对象,也就是引用类型,"=="操作符比较的是对象在内存中的地址(即是否为同一个对象)。Integer不是java中的基础数据类型,Integer是int的包装类,属于对象,所以例子中的System.out.println(a == b);System.out.println(c == d);是判断a对象和b对象、c对象和d对象的内存地址是否相等。

那么为什么会出现一个是true一个是false的结果呢?我们来看下JDK的源码:

ini 复制代码
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;
        //就是这里初始化[-128,127]这个范围的数据放入到cache数组中。
        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() {}
}

通过翻阅Integer类的源码,我们发现,Integer类中有一个名为IntegerCache的静态内部类,IntegerCache类中有一个static静态代码块,java静态代码块会在类加载时运行。IntegerCache类中有一个Integer类型的cache数组,系统启动的时候就会初始化[-128,127]这个范围的数值放入cache数组中,看debug截图:

我们再来看看Integer a = 20;这行代码,在执行Integer a = 20;的时候,底层是会进行自动装箱的:

ini 复制代码
Integer a = 20;
//底层会进行自动装箱
Integer a = Integer.valueOf(20);

来看下valueOf方法的源码:

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

总结:

i的值 >= -128并且 <= 127的时候,就直接从IntegerCache类中的cache数组里面取,然后返回;否则的话,就调用new Integer方法去创建新的Integer对象。至于为什么是[-128,127]这个区间呢?是因为这个范围内的数值我们平时用的比较多。这是程序开发中的池化思想,对于常用的整数值,直接从缓存池中获取对象,减少了对象的创建和垃圾回收的开销。

相关推荐
我叫黑大帅6 分钟前
Go 语言并发编程的 “工具箱”
后端·面试·go
用户83562907805138 分钟前
Python 实现 PowerPoint 形状动画设置
后端·python
用户908324602731 小时前
Spring Boot 缓存架构:一行配置切换 Caffeine 与 Redis,透明支持多租户隔离
后端
tyung1 小时前
zhenyi-base 开源 | Go 高性能基础库:TCP 77万 QPS,无锁队列 16ns/op
后端·go
子兮曰1 小时前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端
桦说编程1 小时前
你的函数什么颜色?—— 深入理解异步编程的本质问题(上)
后端·性能优化·编程语言
百度地图汽车版2 小时前
【AI地图 Tech说】第九期:让智能体拥有记忆——打造千人千面的小度想想
前端·后端
臣妾没空2 小时前
Elpis 全栈框架:从构建到发布的完整实践总结
前端·后端
喷火龙8号2 小时前
单 Token 认证方案的进阶优化:透明刷新机制
后端·架构
孟沐2 小时前
Java异常处理知识点整理(大白话版)
后端