JDK源码解析 Integer类使用了享元模式
生活随笔
收集整理的這篇文章主要介紹了
JDK源码解析 Integer类使用了享元模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JDK源碼解析
Integer類使用了享元模式。
我們先看下面的例子:
public class Demo {public static void main(String[] args) {Integer i1 = 127;Integer i2 = 127; ?System.out.println("i1和i2對象是否是同一個對象?" + (i1 == i2)); ?Integer i3 = 128;Integer i4 = 128; ?System.out.println("i3和i4對象是否是同一個對象?" + (i3 == i4));} }運行上面代碼,結果如下:
為什么第一個輸出語句輸出的是true,第二個輸出語句輸出的是false?
通過反編譯軟件進行反編譯,代碼如下:
public class Demo {public static void main(String[] args) {Integer i1 = Integer.valueOf((int)127);Integer i2 Integer.valueOf((int)127);System.out.println((String)new StringBuilder().append((String)"i1\u548ci2\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i1 == i2)).toString());Integer i3 = Integer.valueOf((int)128);Integer i4 = Integer.valueOf((int)128);System.out.println((String)new StringBuilder().append((String)"i3\u548ci4\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i3 == i4)).toString());} }上面代碼可以看到,直接給Integer類型的變量賦值基本數據類型數據的操作底層使用的是?valueOf()?,所以只需要看該方法即可
public final class Integer extends Number implements Comparable<Integer> {public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[]; ?static {int 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) {}}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() {}} }可以看到?Integer?默認先創建并緩存?-128 ~ 127?之間數的?Integer?對象,
當調用?valueOf?時如果參數在?-128 ~ 127?之間則計算下標并從緩存中返回,
否則創建一個新的?Integer?對象。
總結
以上是生活随笔為你收集整理的JDK源码解析 Integer类使用了享元模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组合模式——透明组合模式,安全组合模式
- 下一篇: JDK源码解析 InputStream类