昨天例行code review時(shí)大家有討論到int和Integer的比較和使用。 這里做個(gè)整理,發(fā)表一下個(gè)人的看法。
【int和Integer的區(qū)別】
- int是java提供的8種原始類型之一,java為每個(gè)原始類型提供了封裝類,Integer是int的封裝類。int默認(rèn)值是0,而Integer默認(rèn)值是null;
- int和Integer(無論是否new)比較,都為true, 因?yàn)闀?huì)把Integer自動(dòng)拆箱為int再去比;
- Integer是引用類型,用==比較兩個(gè)對(duì)象,其實(shí)比較的是它們的內(nèi)存地址,所以不同的Integer對(duì)象肯定是不同的;
- 但是對(duì)于Integer i=,java在編譯時(shí)會(huì)將其解釋成Integer i=Integer.valueOf();。但是,Integer類緩存了[-128,127]之間的整數(shù), 所以對(duì)于Integer i1=127;與Integer i2=127; 來說,i1==i2,因?yàn)檫@二個(gè)對(duì)象指向同一個(gè)內(nèi)存單元。 而Integer i1=128;與Integer i2=128; 來說,i1==i2為false。
【各自的應(yīng)用場景】
- Integer默認(rèn)值是null,可以區(qū)分未賦值和值為0的情況。比如未參加考試的學(xué)生和考試成績?yōu)?的學(xué)生
- 加減乘除和比較運(yùn)算較多,用int
- 容器里推薦用Integer。 對(duì)于PO實(shí)體類,如果db里int型字段允許null,則屬性應(yīng)定義為Integer。 當(dāng)然,如果系統(tǒng)限定db里int字段不允許null值,則也可考慮將屬性定義為int。
- 對(duì)于應(yīng)用程序里定義的枚舉類型, 其值如果是整形,則最好定義為int,方便與相關(guān)的其他int值或Integer值的比較
- Integer提供了一系列數(shù)據(jù)的成員和操作,如Integer.MAX_VALUE,Integer.valueOf(),Integer.compare(),compareTo(),不過一般用的比較少。建議,一般用int類型,這樣一方面省去了拆裝箱,另一方面也會(huì)規(guī)避數(shù)據(jù)比較時(shí)可能帶來的bug。
【附:Integer類的內(nèi)部類IntegerCache和valueOf方法代碼】
public final class Integer extends Number implements Comparable<Integer> {
//。。。。。。。。。。。。
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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//。。。。。。。。。。。。。
}