#javase5之后就開始支持自動(dòng)拆裝箱了,說這個(gè)之前先看看下面的程序:
public class TestIntegerAndint{
public static void main(String[] args) {
int a=100;
Integer b=100;
System.out.println(a==b);
Integer c=100;
Integer d=100;
System.out.println(c==d);
Integer e=200;
Integer f=200;
System.out.println(e==f);
}
}
看到答案你們可能會(huì)有點(diǎn)驚訝
image.png
這里咱們來分析一下若债,第一個(gè)是java進(jìn)行了自動(dòng)拆箱,所以true這個(gè)大家應(yīng)該可以理解
第二個(gè)因?yàn)?Integer類的內(nèi)部有一個(gè)IntegerCache緩存類减江;實(shí)際上就是緩存了一個(gè)大小為256的Integer數(shù)組;把-128 ~ 127之間的所有Integer對(duì)象都提前創(chuàng)建好捻爷,緩存在數(shù)組中辈灼,方便后面使用; 目的是為了提高性能和節(jié)約空間; 當(dāng)定義一個(gè)不在-128 ~ 127之間的Integer對(duì)象時(shí)也榄,會(huì)新創(chuàng)建一個(gè)Integer對(duì)象
這個(gè)也能很好的解釋為什么第三個(gè)情況是false.