先看一段测试结果:

/*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进行优化。

最新文章

  1. Phantomjs+Nodejs+Mysql数据抓取(1.数据抓取)
  2. [SharePoint 2010] Modify lookup mapping with PowerShell
  3. jquery图片轮播,单张图片轮播时间不同
  4. Eclipse插件的安装方法
  5. C# addin 开发心得记录
  6. 【从0到1学Web前端】CSS伪类和伪元素
  7. YII 1.0 发表文章用到的小物件
  8. 2011 Multi-University Training Contest 1 - Host by HNU
  9. 常用SQL_官方文档使用
  10. OpenPop.NET
  11. python编写shell脚本
  12. C# 正则表达式中的顺序环视和逆序环视
  13. PHP开发——数据类型
  14. Ubuntu 16.04 安装 arm-linux-gcc 交叉编译工具
  15. ERROR 2002 (HY000): Can&#39;t connect to local MySQL server through socket &#39;/var/lib/mysql/mysql.sock&#39; (2) 的解决办法
  16. cocos2d-js 调试办法 断点调试 Android真机调试
  17. Linux 下 less 命令
  18. ssh远程调用之shell脚本远程调用应用程序
  19. HPUX修改disk实例号--11.31only
  20. .........请添加一个名为 jquery (区分大小写)的 ScriptResourceMapping。

热门文章

  1. CVE-2012-1876漏洞分析
  2. C# asp.net 实现导出Excel
  3. Http 请求 GET和POST的区别
  4. 在C#中使用CURL
  5. 洛谷P2323 [HNOI2006] 公路修建问题 [二分答案,生成树]
  6. java中的静态绑定与动态绑定
  7. properties文件乱码问题 eclipse
  8. Hibernate对象的状态转换
  9. 前端获取Base64字符串格式图片Ajax到后端处理
  10. (bc 1002)hdu 6016 count the sheep