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

相关推荐
是小蟹呀^18 小时前
Spring Security + JWT 面试题整理
java·jwt·springsecurity
spencer_tseng20 小时前
Redis + Nacos.bat
java·windows·dos
霸道流氓气质20 小时前
SpringBoot中通用工具类库(Utils)封装与使用实践
spring boot·后端·python
troyzhxu20 小时前
列表查询的 GraphQL —— 一行代码终结你的 if-else 地狱!
java·springboot·graphql
孫治AllenSun21 小时前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
好好沉淀1 天前
@NotBlank(message = “{xxx}“) 注解中花括号的含义
java
fīɡЙtīиɡ ℡1 天前
内存泄漏产生的原因
java·spring·servlet
hkj88081 天前
Ubuntu 切换java版本
java·linux·ubuntu