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

最新文章

  1. elastichq 离线安装
  2. 独自handle一个数据库大程有感
  3. UVA 11809 - Floating-Point Numbers
  4. SparkStreaming入门及例子
  5. C# JackLib系列之如何获取地球上两经纬度坐标点间的距离
  6. 【MySQL for Mac】终极解决——MySQL在Mac的字符集设置
  7. bzoj1293
  8. SpringInAction读书笔记--第4章面向切面
  9. Method to fix &quot;Naming information cannot be located because the target principal name is incorrect.&quot; for AD replication failure
  10. Spring起步(一)Building a RESTful Web Service
  11. 为什么ABAP开发者需要使用面向对象技术?
  12. Python中模块之copy的功能介绍
  13. gitbook安装与使用,并使用docker部署
  14. Java日期时间处理
  15. mysql之 redo log
  16. 解决mysql开启GTID主从同步出现1236错误问题
  17. 0002python中dict和list的特殊构造
  18. Linux系统——MySQL基础(二)
  19. Perl 获得当前路径
  20. 漂亮!Javascript代码模仿淘宝宝贝搜索结果的分页显示效果

热门文章

  1. Javascript 排序算法(转)
  2. 【转】mysql INSERT的用法
  3. RaspberryPi cProfile使用
  4. Python数据科学安装Numby,pandas,scipy,matpotlib等(IPython安装pandas)
  5. Android 知识Tips
  6. HTML form without CSRF protection,HTML表单没有CSRF保护
  7. 动软生成器添加Mysql注释
  8. HTML &lt;section&gt; 标签
  9. HDU_2544_最短路
  10. 05C语言数组