Java中的整数实例和int原始值比较

Shi*_*rty 2 java

Integer a = 5;
int b = 5;

System.out.println(a==b); // Print true
Run Code Online (Sandbox Code Playgroud)

但是为什么这个打印是真的,因为a是a的实例Integer而b是原始的int

Dar*_*ila 12

Java使用Unboxing比较基元和包装类时的概念.Integer变量中的哪个位置被转换为基本int类型.

以下是您的代码所发生的事情:

Integer a = 5; //a of type Integer i.e. wrapper class
int b = 5; //b of primitive int type

System.out.println(a==b) // a is unboxed to int type and compared with b, hence true
Run Code Online (Sandbox Code Playgroud)

有关更多信息Autoboxing(反向拆箱)和Unboxing 链接.