java integer對象判斷兩個數字是否相等,不一定對
問題發生的背景:javaweb的項目,起先,因為在java中實體類中的int類型在對象初始化之后會給int類型的數據默認賦值為0,這樣在很多地方就會出現不必要的錯誤,比如沒有判斷之后就來計算分頁,那么就可能出現頁碼為負數的情況,同時我也看了一片相關的blog,大概意思就是在javaweb中出現的這個問題,盡量不要用int。
好了受了這些影響,我在實體類里很多地方就用了integer類型,前幾天都沒有發現問題,在昨天做一個數據庫相關的操作時,要將兩個實體類的某些屬性進行比較,(兩個實體類中產品的Id)數據也比較巧,id=127 接下來就是id=132,然后在循環中發現127以前的數據比較結果為相等,127以后,從132開始比較時,后面所有的記錄都不相等,奇怪了,132明明等於132啊,說到這里有的朋友應該猜到了並且笑了。好吧。還有朋友也會和我第一次遇到這個問題一樣不明白啊。好,先看demo
public void testIntegerAndInt() { Integer a = 128; Integer b = 128; if (a==b) { System.out.print("Integer Compare Integer : "); System.out.println("Y"); }else { System.out.print("Integer Compare Integer : "); System.out.println("N"); } Integer m = 127; Integer n = 127; if (m==n) { System.out.print("int Compare int : "); System.out.println(" Y "); } else { System.out.print("int Compare int : "); System.out.println(" N "); } }
看到了吧,2X2應該由4種組合,但是現在之后2中剩余的來中就不測試了,如果感興趣可以自己試試
下面在深入的看看為啥
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
大概意思就是-128到127之間不會封裝對象而是用常量池的值,不在這個范圍才會創建對象。
最后今天無意間發現了一個很有用的blog
http://blog.csdn.net/jackfrued/article/details/44921941
收藏了