Java中Integer和int的使用及注意點(diǎn)
1. Integer緩存了-128到127之間的值
不在這個(gè)范圍,比較值時(shí)需要用equals()方法
- 在這個(gè)范圍內(nèi),Integer.value(int i) 將返回相同的對(duì)象實(shí)例。
- 超出這個(gè)范圍,每次調(diào)用都會(huì)創(chuàng)建新的Integer對(duì)象。
- Long也是。
public static void main(String[] args) { // Integer和Long都是緩存在-128~127之間,所以可以直接比較,不用equals Integer i1 = 127; Integer i2 = 127; System.out.println(i1 == i2); System.out.println(i1.equals(i2)); System.out.println("====="); Integer i3 = 128; Integer i4 = 128; System.out.println(i3 == i4); System.out.println(i3.equals(i4)); System.out.println("====="); Long ii1 = 127L; Long ii2 = 127L; Long ii3 = 128L; Long ii4 = 128L; System.out.println(ii1 == ii2); System.out.println(ii3 == ii4); System.out.println(ii1.equals(ii2)); System.out.println(ii3.equals(ii4)); }
- 打?。?/li>
true
true
=====
false
true
=====
true
false
true
true
Integer的equals方法源碼
private final int value; public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }
結(jié)論:
- 通過(guò)equals()源碼可以看到它是比較的Integer中具體的值,
- 所以我們?nèi)绻潜容^對(duì)象或者比較-128~127的值可以用==,
- 而如果比較其他的值就需要用equals()了
2. 由于int類型是基本數(shù)據(jù)類型,Integer拆箱時(shí)不能為空
- 例1:
public static void main(String[] args) { // 由于int類型是基本數(shù)據(jù)類型,拆箱時(shí)不能為空 // 例1 Integer i5 = null; System.out.println(i5 == 3); }
報(bào)錯(cuò):
- 例2:
public static void main(String[] args) { // 由于int類型是基本數(shù)據(jù)類型,拆箱時(shí)不能為空 // 例2 Integer i5 = null; test1(i5); } public static void test1(int i) { System.out.println(i); }
結(jié)論:
- 除了緩存導(dǎo)致比對(duì)值可能出現(xiàn)問(wèn)題之外,
- 我們熟知的Integer是包裝類,可以為null,int是基本數(shù)據(jù)類型,不可以為null,
- 在這一點(diǎn)上別忘了包裝類拆箱時(shí)不能為null的問(wèn)題。
- 所有包裝類拆箱成基本數(shù)據(jù)類型時(shí)都存在此問(wèn)題。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring boot與ktor整合的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于spring boot與ktor整合的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Spring使用AspectJ注解和XML配置實(shí)現(xiàn)AOP
這篇文章主要介紹了Spring使用AspectJ注解和XML配置實(shí)現(xiàn)AOP的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10idea?springBoot項(xiàng)目自動(dòng)注入mapper為空?qǐng)?bào)錯(cuò)的解決方法
這篇文章主要介紹了idea?springBoot項(xiàng)目自動(dòng)注入mapper為空?qǐng)?bào)錯(cuò)的解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03Mybatis Plus條件構(gòu)造器ConditionConstructor用法實(shí)例解析
這篇文章主要介紹了Mybatis Plus條件構(gòu)造器ConditionConstructor用法實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08JAVA生產(chǎn)者消費(fèi)者(線程同步)代碼學(xué)習(xí)示例
這篇文章主要介紹了JAVA線程同步的代碼學(xué)習(xí)示例,大家參考使用吧2013-11-11