日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

用int还是用Integer?

發(fā)布時間:2023/12/18 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用int还是用Integer? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
昨天例行code review時大家有討論到int和Integer的比較和使用。 這里做個整理,發(fā)表一下個人的看法。 【int和Integer的區(qū)別】
  • int是java提供的8種原始類型之一,java為每個原始類型提供了封裝類,Integer是int的封裝類。int默認(rèn)值是0,而Integer默認(rèn)值是null;
  • int和Integer(無論是否new)比較,都為true, 因為會把Integer自動拆箱為int再去比;
  • Integer是引用類型,用==比較兩個對象,其實比較的是它們的內(nèi)存地址,所以不同的Integer對象肯定是不同的;
  • 但是對于Integer i=*,java在編譯時會將其解釋成Integer i=Integer.valueOf(*);。但是,Integer類緩存了[-128,127]之間的整數(shù), 所以對于Integer i1=127;與Integer i2=127; 來說,i1==i2,因為這二個對象指向同一個內(nèi)存單元。 而Integer i1=128;與Integer i2=128; 來說,i1==i2為false。
【各自的應(yīng)用場景】
  • Integer默認(rèn)值是null,可以區(qū)分未賦值和值為0的情況。比如未參加考試的學(xué)生和考試成績?yōu)?的學(xué)生
  • 加減乘除和比較運算較多,用int
  • 容器里推薦用Integer。 對于PO實體類,如果db里int型字段允許null,則屬性應(yīng)定義為Integer。 當(dāng)然,如果系統(tǒng)限定db里int字段不允許null值,則也可考慮將屬性定義為int。
  • 對于應(yīng)用程序里定義的枚舉類型, 其值如果是整形,則最好定義為int,方便與相關(guān)的其他int值或Integer值的比較
  • Integer提供了一系列數(shù)據(jù)的成員和操作,如Integer.MAX_VALUE,Integer.valueOf(),Integer.compare(),compareTo(),不過一般用的比較少。建議,一般用int類型,這樣一方面省去了拆裝箱,另一方面也會規(guī)避數(shù)據(jù)比較時可能帶來的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 propertyint 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_VALUEh = 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);}//。。。。。。。。。。。。。}

?

?

ref:java中申明變量用 int 還是 Integer?http://bbs.csdn.net/topics/360102986

ref:Integer與int的種種比較https://www.cnblogs.com/liuling/archive/2013/05/05/intAndInteger.html

轉(zhuǎn)載于:https://www.cnblogs.com/buguge/p/8028502.html

總結(jié)

以上是生活随笔為你收集整理的用int还是用Integer?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。