【Java面试】127等于127,128不等于128?聊聊Java中Integer的八股文

前言

在面试中,Java的等于判断是最常见的,其中Integer的等于判断是众多面试者中最容易出错的。例如:

java 复制代码
public static void main(String[] args) {
    Integer a = 127;
    Integer b = 127;
    System.out.println(a == b);

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

请问,分别输出什么呢?

Integer是什么?

Integer是Java中的包装类,我们经常定义的 Integer a = 1,编译器会帮我们转化为 Integer a = Integer.valueOf(1)的形式。

为什么要用包装类?

1、面向对象考虑,可以让"整型"支持一些方法

2、null值考虑,基本数据类型自身没办法表示null

3、泛型考虑

Integer如何做等于判断?

Integer属于对象,对象之间的判等,无特殊情况都建议通过equals方法进行。如果Integer直接用等于号判断是否相等,可能出现部分情况为true,部分情况为false的现象。

Integer等于判断,什么时候会为false?

大于127,小于-128会为false。这是因为默认情况下JVM会把 -128,127这个区间的Integer给缓存起来,当我们定义Integer的时候,如果位于这个区间,就不会去创建一个新的对象,而是返回缓存中的对象。所以位于该区间的Integer通过等于号判断会是相等的,因为是同一个对象。

查看Integer源码,可以看到Integer缓存操作

java 复制代码
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() {}
}

再查看valueOf方法,如果位于缓存区间,会直接返回缓存中的对象,否则会创建一个新对象。

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

所以,如果不在缓存区间,会创建新对象,那么区间之外的等于判断就会输出false,因为等于在Java中是判断两个对象地址是否相等。

回到最开始的题目,我们不难得出结论,分别输出true和false。

相关推荐
颜进强4 小时前
16 · NestJS LifecycleEvents 生命周期事件:五个钩子、三条边界,和 rag-server 的优雅停机
前端·后端·ai编程
重生之小比特4 小时前
【C++进阶】map和set
java·开发语言·c++
GetcharZp4 小时前
定位不再一个个吐坐标:英伟达 LocateAnything 上手全攻略
后端
需要8264 小时前
分布式事务:Seata AT/TCC/SAGA 的取舍与踩坑
java·spring boot·分布式·spring·spring cloud
晨小安5 小时前
ThreadLocal及其内存泄漏问题深度解析
java·jvm·tomcat·哈希表
m0_587383005 小时前
深圳24小时自助健身房解决方案实战:从系统架构到部署指南
java·人工智能·spring boot·spring·系统架构·需求分析
郑州光合科技余经理5 小时前
同城电商系统:库存变更怎么同步到订单
java·开发语言·前端·后端·uni-app·php·ai编程
我叫黑大帅5 小时前
Go日志库工程选型与逃逸分析评测报告
后端·面试·go
无序的浪6 小时前
测试博客-基于微服务的在线判题系统
java·spring cloud·docker·微服务·测试·在线判题
xfan_me6 小时前
维修保养记录精准版 API 对接实战指南
java·大数据·python