Java装箱==的池化坑

本文深入分析了Java中基本类型与装箱类型Integer在比较操作上的性能差异,通过源码解析指出使用==操作符进行比较时存在的问题,并提出优化策略,推荐使用equals()或XXXValue()方法来提高比较效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创作品,出自 “晓风残月xj” 博客,欢迎转载,转载时请务必注明出处(http://blog.youkuaiyun.com/xiaofengcanyuexj)。

由于各种原因,可能存在诸多不足,欢迎斧正!

        今天读《Effective Java》,读到“基本类型优于装箱基本类型” ,其中那个Integer例子觉得不合适,于是看了Integer源码,发现还真是有点问题,至少我的jdk1.7是有问题的。

     Java是高度封装基于JVM API的语言,和C++一个重要的区别就是不支持运算符重载。就我肤浅地理解,基本的运算操作+、-、*、/、==等对于开发者老说通常是不透明的,所以对于模糊的地方不好把握,对于装饰器类型也就是通常意思的装箱类型,如下:                                                             

int(4字节) Integer
byte(1字节) Byte
short(2字节) Short
long(8字节) Long
float(4字节) Float
double(8字节) Double
char(2字节) Character
boolean(未定) Boolean


        ==对于装箱类型是不好把握的。以Integer为例,通常在[-128,127](其中127取决于JDK中的)系统变量,具体如下:

 String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 

    由于比较简单,直接上实例代码的

/**
 * @功能: Java测试类
 * @authord: jin.xu
 * @version: v1.0.0
 * @see:
 * @date: 2016/1/30 11:49
 */
public class Test {

    public static void main(String[] args) {
        Integer i=127;
        Integer j=127;

        if(j==i){
            System.out.println("true");
        }else{
            System.out.println("false");
        }


        Integer k=128;
        Integer t=128;
        if(k==t){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

    }
}
输入结果分别是:

true
false

      具体原因应该说是jdk还不能说是JVM将小范围的数值做了缓存,如int的[-128,127](其中128并不是一个比较准确的答案),new对象的时候不是直接在堆上创建,而是从常量池中读取,避免频繁创建对象。我们知道,在堆上创建对象是有系统开销的,而池化技术可以在一定程度上解决这类问题,如内存池、线程池等。当然,像jdk这类直接选定数值的方法也是比较粗糙的,还好其中的integerCacheHighPropValue 变量可以针对不同机器作调整。具体直接贴jdk代码的

 /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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() {}
    }


     所以建议是对于装箱类型,比较数值的时候最好直接使用equal()或者XXXValue()方法,避免使用运算符==。自己踩过或者躲过的坑,希望别人也不要踩。

    

     最近空闲时间有看源代码的习惯,如雅虎基于在线机器学习开源爬虫anthelion和dubbo的






               

  






      

            




### Java 中 `Integer` 类型的等于比较 在 Java 中,对于 `Integer` 对象使用 `==` 和 `equals()` 方法进行比较会得到不同的结果。具体来说: - 当使用 `==` 比较两个 `Integer` 对象时,实际上是在比较它们的内存地址而非实际数值。这意味着即使两个不同对象包含相同的整数值,只要它们不是同一个实例,`==` 将返回 `false`[^2]。 例如: ```java Integer c = 128; Integer d = 128; System.out.println(c == d); // 输出: false ``` 然而,由于 JVM 的优化机制——自动装箱缓存(Autoboxing Cache),当 `Integer` 值位于 `-128` 至 `127` 范围内时,JVM 会对这些值进行缓存处理,使得相同范围内的 `Integer` 实例共享同一份内存空间。因此在这个范围内使用 `==` 可能会出现意外的结果。 而 `equals()` 方法则是用来比较两个 `Integer` 对象的实际数值是否相等。无论 `Integer` 是否超出上述提到的缓存区间,`equals()` 总是比较其内部存储的具体数值而不是引用本身[^3]。 下面是一个完整的例子展示两者的差异: ```java public class Main { public static void main(String[] args) { Integer a = new Integer(10); Integer b = new Integer(10); System.out.println(a == b); // 输出: false (因为a和b是两个独立的对象) System.out.println(a.equals(b)); // 输出: true (因为两者表示相同的数值) Integer e = 127; Integer f = 127; System.out.println(e == f); // 输出: true (得益于自动装箱缓存) System.out.println(e.equals(f)); // 输出: true Integer g = 128; Integer h = 128; System.out.println(g == h); // 输出: false (超过缓存范围) System.out.println(g.equals(h)); // 输出: true } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值