Happyjava's blog site

Happyjava's blog site,分享编程知识,顺便发发牢骚

0%

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

前言

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

1
2
3
4
5
6
7
8
9
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缓存操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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方法,如果位于缓存区间,会直接返回缓存中的对象,否则会创建一个新对象。

1
2
3
4
5
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。