Java Integer及int裝箱拆箱對(duì)比
示例代碼:
class BoxIntInteger { public static void main(String[] args) { Integer a = new Integer(10111); int b = 10111; boolean equal1 = a == b; boolean equal2 = a.equals(b); System.out.println(equal1); System.out.println(equal2); }}
反編譯字節(jié)碼:
public static void main(String args[]){ Integer a = new Integer(10111); int b = 10111; boolean equal1 = a.intValue() == b; boolean equal2 = a.equals(Integer.valueOf(b)); System.out.println(equal1); System.out.println(equal2); }
1:可以看出對(duì)于Integer與int使用==比較大小的話,優(yōu)先Integer拆箱。
2: 如果使用equals比較大小的話,則int裝箱。
提示:對(duì)于Integer與int之間大小比較優(yōu)先使用equals比較,否則容易出現(xiàn)空指針,例如:
Integer c= null;System.out.println(c==1);
原因:由于Integer需要調(diào)用intValue進(jìn)行拆箱,因而空指針。
Integer與Integer必須使用equals方法比較,這個(gè)就不必解釋了。但是通常我們可以看先Integer與Integer之間使用==也可以正確比較,原因是:Integer對(duì)于-128到127之間的數(shù)字在緩存中拿,不是創(chuàng)建新對(duì)象。
緩存獲取數(shù)據(jù)源碼:java.lang.Integer#valueOf(int)
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS清除浮動(dòng)方法匯總2. XML 非法字符(轉(zhuǎn)義字符)3. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. React優(yōu)雅的封裝SvgIcon組件示例5. CSS百分比padding制作圖片自適應(yīng)布局6. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))7. TypeScript實(shí)現(xiàn)十大排序算法之歸并排序示例詳解8. 不要在HTML中濫用div9. 深入了解React中的合成事件10. XML入門的常見問題(三)
