【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。

相关推荐
sky_ph6 分钟前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
涡能增压发动积11 分钟前
一起来学 Langgraph [第二节]
后端
IDRSolutions_CN28 分钟前
PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第二部分)
java·经验分享·pdf·软件工程·团队开发
hello早上好31 分钟前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
roman_日积跬步-终至千里31 分钟前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
HelloWord~2 小时前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧2 小时前
黑马点评【基于redis实现共享session登录】
java·redis
00后程序员2 小时前
提升移动端网页调试效率:WebDebugX 与常见工具组合实践
后端
HyggeBest2 小时前
Mysql的数据存储结构
后端·架构
TobyMint2 小时前
golang 实现雪花算法
后端