今天在一个java群里,看到有个群友问到如下为什么第一个为true,第二个为false。  

  System.out.println(Integer.valueOf("50")==Integer.valueOf("50"));   //true
  System.out.println(Integer.valueOf("200")==Integer.valueOf("200"));  //false

  由于一开始他问的第二句,我还想当然的以为是new的对象,肯定不一样,但是为什么第一句为true呢,后来通过查找资料发现

  1、https://www.zhihu.com/question/29879295/answer/102396251  

  2、http://blog.csdn.net/chengzhezhijian/article/details/9628251

    /**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}

  

 private static class IntegerCache {
static final int high;
static final Integer cache[]; static {
final int low = -128; // high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
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() {}
}

  valueOf会将常用的值(-128 to 127)cache起来。当i值在这个范围时,会比用构造方法Integer(int)效率和空间上更好。

  

最新文章

  1. 艺萌TCP文件传输及自动更新系统介绍(TCP文件传输)(四)
  2. SQLServer日期格式化
  3. IOS - Create Push Segue Animation Without UINavigationController
  4. 内存缓存机制and垃圾回收机制
  5. DOS批处理不支持将UNC 路径作为当前目录的巧妙解决方案
  6. 详解JavaScript函数模式
  7. linux 病毒 sfewfesfs
  8. ruby 学习 -- string --1
  9. Html Meta 标签详解
  10. pyenv简介——Debian/Ubuntu中管理多版本Python
  11. Java之利用Socket获取网站内容
  12. 使用device.js检测设备并实现不同设备展示不同网页
  13. POJ 3176-Cow Bowling(DP||记忆化搜索)
  14. python通过http请求发送soap报文进行webservice接口调用
  15. [HCNA]VLAN配置Trunk接口
  16. Access Treeview树节点代码二
  17. 将字符串存储到注册表中,长度一定是 strlen(text) + 1
  18. BZOJ 3620: 似乎在梦中见过的样子
  19. CentOS安装Subversion 1.9.*版本客户端
  20. Calendar获取当前年份、月份、日期

热门文章

  1. 从客户发送http请求到服务器返回http之间发生了什么
  2. Android笔记(二十三) Android中的ProgressBar(进度条)
  3. 【kernel】Centos 云上升级内核失败 如何处理【笔记记录转】
  4. ES6 解构赋值详解
  5. P1330 封锁阳光大学[搜索+染色]
  6. php遍历目录与文件夹的多种方法详解
  7. 在 windows 上安装 git 2.22
  8. 专为简化 C 开发而设计的编程语言 Trad
  9. Maximum Average Subarray II
  10. @select注解中可以用条件构造器