https://www.jianshu.com/p/ff535284916f
【int和Integer的區別】
- int是java提供的8種原始類型之一,java為每個原始類型提供了封裝類,Integer是int的封裝類。int默認值是0,而Integer默認值是null;
- int和Integer(無論是否new)比較,都為true, 因為會把Integer自動拆箱為int再去比;
- Integer是引用類型,用==比較兩個對象,其實比較的是它們的內存地址,所以不同的Integer對象肯定是不同的;
- 但是對於Integer i=,java在編譯時會將其解釋成Integer i=Integer.valueOf();。但是,Integer類緩存了[-128,127]之間的整數, 所以對於Integer i1=127;與Integer i2=127; 來說,i1==i2,因為這二個對象指向同一個內存單元。 而Integer i1=128;與Integer i2=128; 來說,i1==i2為false。
【各自的應用場景】
- Integer默認值是null,可以區分未賦值和值為0的情況。比如未參加考試的學生和考試成績為0的學生
- 加減乘除和比較運算較多,用int
- 容器里推薦用Integer。 對於PO實體類,如果db里int型字段允許null,則屬性應定義為Integer。 當然,如果系統限定db里int字段不允許null值,則也可考慮將屬性定義為int。
- 對於應用程序里定義的枚舉類型, 其值如果是整形,則最好定義為int,方便與相關的其他int值或Integer值的比較
- Integer提供了一系列數據的成員和操作,如Integer.MAX_VALUE,Integer.valueOf(),Integer.compare(),compareTo(),不過一般用的比較少。建議,一般用int類型,這樣一方面省去了拆裝箱,另一方面也會規避數據比較時可能帶來的bug。
【附:Integer類的內部類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); } //。。。。。。。。。。。。。 }
java POJO中 Integer 和 int 的不同
我的選擇是包裝類好!原因如下:
1。所有的sql使用的默認類型都是null,如果你把POJO中的映射屬性類型寫為基本類型,當查找不到記錄的時候,返回null賦給基本類型就會出錯
2。包裝類型都可以相應的轉化為基本類型,如果你設置為基本類型比如int的話,它默認初始化為0,但0本身就代表着一種含義,如果為null的話,既好理解,也可以方便開發人員轉化!而且很多xml配置中默認都是null。