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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何给数据添加高斯白噪声?
- 下一篇: javaweb 从数据库读取数据的详细操