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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Integer的值范围-128~127

發布時間:2024/3/12 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Integer的值范围-128~127 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

看到一道面試題,這個面試題是這樣的。

public class Foo {public static void main(String[] args) {Integer a = 120,b = 160;Integer c = 120,d = 160;System.out.println(a==c);System.out.println(a.equals(c));System.out.println(b==d);System.out.println(b.equals(d));} }

運行結果:

那么,會看到為什么 a==c 就是true, 而b==d 就是false了呢?

其實這樣的,當我們給一個Integer賦予一個int類型的值的時候它會調用Integer的靜態方法ValueOf()方法。

Integer a = Integer.valueOf(120);

Integer c?= Integer.valueOf(120);

Integer b?= Integer.valueOf(160);

Integer d?= Integer.valueOf(160);

那這個valueOf()方法返回的integer是不是一個新的new Integer(120)?那這樣的話它們應該為 == 為false,那么下面看下源碼

public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}

這個源碼中的方法,他會拿我們賦值的int值去判斷是否存在緩存類的low和hign范圍之間,如果我們int值在這個范圍之間的話,取的是緩存類中的cache緩存數組中取值,否則的話就是new Integer(num);

那么這個緩存類integerCache是什么呢?看源碼

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) {try {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = 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的范圍,并且放到一個靜態緩存數組cache中。在類加載時就將-128 到 127 的Integer對象創建了,并保存在cache數組中。

其實就一句話:

一旦程序調用valueOf 方法,如果i的值是在-128 到 127 之間就直接在cache緩存數組中去取Integer對象。而不在此范圍內的數值則要new到堆中了。

延伸:

public class Foo {public static void main(String[] args) {Integer in = new Integer(12);int t = 12;System.out.println(t == in);} }

結果:

為什么int和integer比較是為true呢?看下反編譯后的代碼

Integer in = new Integer(12); int t = 12; System.out.println(t == in.intValue());

這個反編譯后的代碼,new Integer的進行了intValue()拆箱,拆箱后為int類型,int類型與int類型比較為true

總結

以上是生活随笔為你收集整理的Integer的值范围-128~127的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。