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

歡迎訪問(wèn) 生活随笔!

生活随笔

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

编程问答

Integer的值范围-128~127

發(fā)布時(shí)間:2024/3/12 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Integer的值范围-128~127 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

看到一道面試題,這個(gè)面試題是這樣的。

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));} }

運(yùn)行結(jié)果:

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

其實(shí)這樣的,當(dāng)我們給一個(gè)Integer賦予一個(gè)int類型的值的時(shí)候它會(huì)調(diào)用Integer的靜態(tài)方法ValueOf()方法。

Integer a = Integer.valueOf(120);

Integer c?= Integer.valueOf(120);

Integer b?= Integer.valueOf(160);

Integer d?= Integer.valueOf(160);

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

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

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

那么這個(gè)緩存類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() {}}

源碼中有一個(gè)靜態(tài)內(nèi)部類,這個(gè)類定義了-128~127的范圍,并且放到一個(gè)靜態(tài)緩存數(shù)組cache中。在類加載時(shí)就將-128 到 127 的Integer對(duì)象創(chuàng)建了,并保存在cache數(shù)組中。

其實(shí)就一句話:

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

延伸:

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

結(jié)果:

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

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

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

總結(jié)

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

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