Integer i1= new Integer(1); Integer i2= new Integer(1); Integer i3=i1+i2; Integer i4=2; System.out.println(i1==i2);//false System.out.println(i3==i4);//true為什么i1==i2是false,但是i3==i4是true呢?
1 回答
已采納

慕粉3233872
TA貢獻(xiàn)70條經(jīng)驗(yàn) 獲得超29個(gè)贊
==操作比較的是兩個(gè)變量的值是否相等,對(duì)于引用型變量表示的是兩個(gè)變量在堆中存儲(chǔ)的地址是否相同,即棧中的內(nèi)容是否相同。
new Integer(1) 和Integer a = 1不同,前者會(huì)創(chuàng)建新的對(duì)象,存儲(chǔ)在堆中,而后者如果在-128到127的范圍內(nèi),不會(huì)創(chuàng)建新的對(duì)象,而是從IntegerCache中獲取。
添加回答
舉報(bào)
0/150
提交
取消