Integer类型的变量使用==比较会如何?

遇到了一个面试题,Integer变量可以使用==比较吗?为什么?

遇到这个问题的时候,首先想到的是Integer变量是对象,使用==比较的是引用的值,但是这样理解是不对的,如下面的代码所示:

Integer a = 122;
Integer b = 123;
a++;
System.out.println(a == b);    // true

实际上,真要说清楚这个问题,还要参考《The Java Language Specification》,这里我参考的是Java SE 8版本。

先说结论,这个问题考察的是数字上下文环境以及封箱和拆箱机制。

在jls8的5.6节中,有这样一段阐述:

Numeric contexts apply to the operands of an arithmetic operator.
Numeric contexts allow the use of:
• an identity conversion (§5.1.1)
• a widening primitive conversion (§5.1.2)
• an unboxing conversion (§5.1.8) optionally followed by a widening primitive
conversion

翻译一下就是:

数字上下文环境适用于算数运算符的操作数。
数字上下文环境允许以下用法:
• 等价转换(如int类型转为int类型);
• 扩宽基本类型(如int向long扩宽);
• 拆箱转换,可以选择性跟一个扩宽转换。

因此,当==两边是Integer时,适用数字上下文环境,拆箱机制触发,相当于两个int基本类型在比较。

实际上,jsl8还介绍了String上下文环境,该上下文环境只针对+操作符,是我们很常见的一种情形:
+的两个操作数其中一个是String类型,而另一个不是时,就适用String上下文环境,非String操作数先向String类型转换,然后应用String的拼接操作符+,最后得到String类型。

    System.out.println(1 + 2 + "hello");    // 3hello
    System.out.println("hello" + 1 + 2);    // hello12

如上面的代码,应用String上下文规则就很容易理解。

-------------------------------------
吾生也有涯,而知也无涯。
原文地址:https://www.cnblogs.com/SanjiApollo/p/12726763.html