直接看问题吧

    for (int i = 0; i < 150; i++) {
Integer a = i;
Integer b = i;
System.out.println(i + " " + (a == b));
}部分结果

结果为:

.....
124 true
125 true
126 true
127 true
128 false
129 false
130 false
131 false

黑人问号?  为什么到128就不行了? 问题在哪里?  (道行太浅!  为什么就认为 false是异端)

查了一下java会自动将(i)int类型转换为Integer类型,即

Integer a = Integer.valueOf(1);

等等,  再仔细思考一下。  结合上述例子,每一次 i和j都会被装箱为Integer   既然是对象,那就不应该返回true了啊?。  那我就用看看 i和j的内存地址()

for(int i=0;i<150;i++){
Integer a=i;
Integer b=i;
System.out.println(a+" "+b+" "+System.identityHashCode(a)+" "+System.identityHashCode(b));
}

部分结果:

1 123 123 1531448569 1531448569
124 124 1867083167 1867083167
125 125 1915910607 1915910607
126 126 284720968 284720968
127 127 189568618 189568618
128 128 793589513 1313922862
129 129 495053715 1922154895

竟然....... 竟然从0到127不同时候自动装箱得到的是同一个对象!从128开始才是正常情况。  那看看源码

    /**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} 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.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

我大概的翻译一下啊,  数再-128到127之间,就直接在缓存里取。否则就返回一个新对象。  哦哦这下问题解决了

最新文章

  1. Day12-mysql&amp;&amp;redis
  2. 一致性哈希算法与Java实现
  3. noi 1.5 43:质因数分解
  4. C++ mem_fun 和 mem_fun_ref 的用法
  5. FMDB中 databaseWithPath 的使用问题
  6. Android Service与Activity之间通信
  7. Linux:Ubuntu14.04离线安装scala(在线安装)
  8. [技巧]如何清除VS2008的最近打开项目
  9. C# 构造函数中调用虚方法的问题
  10. 【Problem】Count and Say
  11. Python中将函数作为另一个函数的参数传入并调用
  12. HDU 2037 今年暑假不AC(贪心,区间更新,板子题)
  13. [bzoj1227] [SDOI2009]虔诚的墓主人
  14. asp.net 使用rabbitmq事例
  15. MySQL 通讯协议
  16. Redis学习系列七分布式锁
  17. CSS3背景色透明(兼容IE8)
  18. FOREIGN MySQL 之 多表查询
  19. 虚拟机安装的ubutun全屏
  20. Lucene 学习-安装 Elasticsearch 服务器

热门文章

  1. window.prompt()和 window.confirm()选择
  2. Hyperledger Fabric(1)基础架构
  3. hive各种报错
  4. Linux SWAP交换分区维护
  5. glsl:error C1105: cannot call a non-function
  6. 使用Pechkin与CPechkin生成PDF
  7. Oracle 导入dump
  8. 权限和ACL练习题
  9. 【LuoguP5383】[模板]普通多项式转下降幂多项式
  10. 基于nc命令监控服务端口的Shell脚本