Java中2個Integer比較相同的四種方式舉例
Java中2個Integer比較相同的4種方式
概要
使用前切記Integer的范圍是 【 -128 ~ 127】例如:Integer a = 128; Integer b = 128;
1,使用== 比較
【-128 ~ 127】區(qū)間內返回true,否則返回false
// == 比較
if (a == b){
System.out.println("a,b使用==比較 返回結果:true");
}else {
System.out.println("a,b使用==比較 返回結果:false");
}
返回false
2,使用equals比較
// equals比較
if (a.equals(b)){
System.out.println("a,b使用equals比較 返回結果:true");
}else {
System.out.println("a,b使用equals比較 返回結果:false");
}
返回true,因為點擊內部equals方法發(fā)現,核心比較的Integer的intValue()值
// 點擊equals時進入該方法
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
3,使用intValue比較
if (a.intValue() == b.intValue()){
System.out.println("a,b使用intValue比較 返回結果:true");
}else {
System.out.println("a,b使用intValue比較 返回結果:false");
}
返回true,核心比較的也是Integer的intValue()值
4,使用 compareTo比較
// compareTo比較
if (a.compareTo(b) == 0){
System.out.println("a,b使用compareTo比較 返回結果:true");
}else {
System.out.println("a,b使用compareTo比較 返回結果:false");
}
返回true,核心比較的是int值
// 點擊compareTo時進入該方法
// 第一級
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
// 第二級
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
總結
Integer大于127后不能用==比較的原因是因為Java的自動裝箱機制和Integer對象的緩存機制,如果是在區(qū)間內則從緩存中獲取返回,否則創(chuàng)建一個新的Integer對象,源碼如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

如果你要賦的值在這【-128 ~ 127】區(qū)間內,他就會把變量a,b當做一個個變量,放到內存中;但如果不在這個范圍內,就會去new一個Integer對象
經過測試,
1》 Integer在【-128 ~ 127】范圍內時,4個方法返回都是true,
2》 小于-128或者大于127時,==返回是false,其余3種方法返回的都是true。
到此這篇關于Java中2個Integer比較相同的四種方式的文章就介紹到這了,更多相關Java中Integer比較相同內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在SpringBoot3中spring.factories配置不起作用的原因和解決方法
本文給大家介紹了在SpringBoot3中spring.factories配置的自動裝配不生效的原因和解決方法,文中通過代碼和圖文給出了詳細的解決方法,具有一定的參考價值,需要的朋友可以參考下2024-02-02
SpringCache緩存抽象之CacheManager與自定義鍵生成方式
本文將深入探討Spring Cache的核心組件CacheManager及自定義鍵生成策略,幫助開發(fā)者掌握緩存配置與優(yōu)化技巧,從而構建高效可靠的緩存系統(tǒng),希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

