zoukankan      html  css  js  c++  java
  • JAVA包装类的缓存范围

    JAVA包装类的缓存范围

    前两天面试遇到两个关于JAVA源码的问题,记录下来提醒自己。

    1.写出下面的输出结果

    System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));    --false
    System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));        --true
    System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128"));     --true
    System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000"));  --false

    当时因为不了解Integer.valueOf(int a)方面底层的实现,所以认为都是进行的对象的==比较,都为false。但是错了正确答案是 false true true false

    后面看了源码才知道,原来如果是a的值在-128到127之间的话,是直接从一个Integer [] cache 的数组中取数;如果不再这个范围内才会new Integer对象。

    下面是相关的源码:

    public static Integer valueOf(int i) {
      assert IntegerCache.high >= 127;
      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 {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
          int i = parseInt(integerCacheHighPropValue);
          i = Math.max(i, 127);
          // Maximum array size is Integer.MAX_VALUE
          h = Math.min(i, Integer.MAX_VALUE - (-low));
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);
      }

      private IntegerCache() {}
    }

    包装器的缓存:

    • Boolean:(全部缓存)
    • Byte:(全部缓存)
    • Character(<= 127缓存)
    • Short(-128 — 127缓存)
    • Long(-128 — 127缓存)
    • Integer(-128 — 127缓存)
    • Float(没有缓存)
    • Doulbe(没有缓存)

    同样对于垃圾回收器来说:

    ru:Integer i = 100;

    i = null;

    这里虽然i被赋予null,但它之前指向的是cache中的Integer对象,而cache没有被赋null,所以Integer(100)这个对象还是存在;然而如果这里是1000的话就符合回收的条件;其他的包装类也是。

    本文转自http://www.cnblogs.com/javatech/p/3650460.html

  • 相关阅读:
    Lua获取当前时间
    标准库
    Cocos2d-x retain和release倒底怎么玩?
    lua 中处理cocos2dx 的button 事件
    探讨把一个元素从它所在的div 拖动到另一个div内的实现方法
    从 ie10浏览器下Symbol 未定义的问题 探索vue项目如何兼容ie低版本浏览器(ie9, ie10, ie 11 )
    setTimeout里无法调用鼠标事件的event
    浅谈HTTP缓存以及后端,前端如何具体实现HTTP缓存
    window7电脑git设置快捷命令
    从获取点击事件根元素谈 target和currentTarget
  • 原文地址:https://www.cnblogs.com/panxuejun/p/7275390.html
Copyright © 2011-2022 走看看