Java判断Integer相等-应该这样用

开发
本文简单分析了下Integer类型的==​比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals。

先看下这段代码,然后猜下结果:

Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1 == i2);
System.out.println(i3 == i4);

针对以上结果,估计不少Java小伙伴会算错!

如果在项目中使用==对Integer进行比较,很容易掉坑。

为什么发生以上结果?

1.执行Integer i1 = 50的时候,底层会进行自动装箱:

Integer i1 = 50;
//底层自动装箱
Integer i = Integer.valueOf(50);

2.再看==操作

==是判断两个对象在内存中的地址是否相等。所以System.out.println(i1 == i2); 和 System.out.println(i3 == i4); 是判断他们在内存中的地址是否相等。

根据猜测应该全是false或者全是true呀,怎么会不同呢?

3.源码底下无秘密

通过翻看jdk源码,你会发现:如果要创建的 Integer 对象的值在 -128 到 127 之间,会从 IntegerCache 类中直接返回,否则才调用 new Integer方法创建。所以只要数值是正的Integer > 127,则会new一个新的对象。数值 <= 127时会直接从Cache中获取到同一个对象。

public static Integer valueOf(int i) {
    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() {}
}

结论

本文简单分析了下Integer类型的==比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals。

同理,Byte、Shot、Long等,也有Cache,各位记得翻看源码!

责任编辑:赵宁宁 来源: 不焦躁的程序员
相关推荐

2021-07-01 16:10:22

equals字符串Java

2021-06-01 11:05:18

Javaa.equals(b)源码

2019-07-28 20:38:33

2020-01-18 18:37:00

Java并行计算数据库

2012-10-11 09:46:20

2018-08-29 11:14:32

2019-12-04 09:05:15

千万级流量高并发

2019-09-19 09:18:02

API网关互联网

2021-02-01 13:35:28

微信Python技巧

2017-10-09 16:27:27

Glide内存加载库

2017-09-30 12:53:28

内存

2023-03-31 07:31:28

SliceGolang

2014-07-28 10:22:05

5G5G网络无线网络

2021-01-22 05:55:12

GitAngularJStype

2021-04-05 14:47:05

装饰器Python代码

2022-09-26 07:32:24

开发接口编程

2017-03-21 15:20:11

数据团队模式思路

2021-06-16 09:10:29

APP开发AndroidiOS

2017-09-29 14:14:04

笔记本视频输出

2021-12-14 10:45:59

智能飞行汽车
点赞
收藏

51CTO技术栈公众号