久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Java Integer及int裝箱拆箱對比

瀏覽:35日期:2022-08-24 16:39:28

示例代碼:

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); }}

反編譯字節碼:

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:可以看出對于Integer與int使用==比較大小的話,優先Integer拆箱。

2: 如果使用equals比較大小的話,則int裝箱。

提示:對于Integer與int之間大小比較優先使用equals比較,否則容易出現空指針,例如:

Integer c= null;System.out.println(c==1);

原因:由于Integer需要調用intValue進行拆箱,因而空指針。

Integer與Integer必須使用equals方法比較,這個就不必解釋了。但是通常我們可以看先Integer與Integer之間使用==也可以正確比較,原因是:Integer對于-128到127之間的數字在緩存中拿,不是創建新對象。

緩存獲取數據源碼: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);}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 昭觉县| 顺义区| 新兴县| 安龙县| 蒙城县| 平潭县| 武鸣县| 长岛县| 桑植县| 肥东县| 黄陵县| 资中县| 尉氏县| 文化| 嘉鱼县| 桐乡市| 健康| 湖口县| 焉耆| 龙州县| 昭苏县| 凤阳县| 新竹县| 星座| 读书| 墨竹工卡县| 富阳市| 潼南县| 钟山县| 淅川县| 武城县| 沂南县| 沈阳市| 原平市| 怀安县| 蓝山县| 顺义区| 凤翔县| 抚顺县| 黔江区| 运城市|