国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

Integer IntegerCache源碼閱讀

2024-07-13 10:16:25
字體:
來源:轉載
供稿:網友

先看一段測試結果:

/*public static void main(String[] args) {    Integer a = 128, b = 128;    Integer c = 127, d = 127;    System.out.println(a == b);//false    System.out.println(c == d);//true  }*/    /*public static void main(String[] args) {    Integer int1 = Integer.valueOf("100");    Integer int2 = Integer.valueOf("100");    System.out.println(int1 == int2);//true  }*/  public static void main(String[] args) {    Integer int1 = Integer.valueOf("300");    Integer int2 = Integer.valueOf("300");    System.out.println(int1 == int2);//false  }

JDK的源碼如下:

public static Integer valueOf(String s) throws NumberFormatException {    return Integer.valueOf(parseInt(s, 10));  }public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)      return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);  }

發現里面另有玄機,多了個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 property      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_VALUE          h = 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() {}  }

原來Integer把-128到127(可調)的整數都提前實例化了。

這就解釋了答案,原來你不管創建多少個這個范圍內的Integer用ValueOf出來的都是同一個對象。

但是為什么JDK要這么多此一舉呢? 我們仔細想想, 淘寶的商品大多數都是100以內的價格, 一天后臺服務器會new多少個這個的Integer, 用了IntegerCache,就減少了new的時間也就提升了效率。同時JDK還提供cache中high值得可配置,

這無疑提高了靈活性,方便對JVM進行優化。

總結

以上就是本文關于Integer IntegerCache源碼閱讀的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南开区| 来凤县| 金乡县| 鹤壁市| 马边| 米易县| 台东市| 堆龙德庆县| 阜南县| 华容县| 峡江县| 阿克陶县| 霍城县| 邯郸县| 中阳县| 军事| 常德市| 浦城县| 葫芦岛市| 鄂温| 富锦市| 岳池县| 沂源县| 玉田县| 清河县| 克山县| 胶州市| 仪陇县| 临猗县| 太和县| 双城市| 磴口县| 隆尧县| 堆龙德庆县| 海盐县| 石景山区| 湛江市| 永胜县| 临夏市| 顺平县| 龙岩市|