A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© just_nnnnx 中级黑马   /  2014-3-20 14:57  /  1039 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 just_nnnnx 于 2014-3-20 15:14 编辑

为什么Integer in1 = 127;
          Integer in2 = 127;

会有  in1 == in2;

          Integer in3 = 128;
          Integer in4 = 128;

       in3 != in4;


3 个回复

倒序浏览
这里用了享元模式,当Integer的值小于127,也就是一个字节的时候它们在内存共用一个对象,当值大于127就从新创建一个对象
回复 使用道具 举报 1 0
这个就关系到Integer的的范围了。
-128~~127
当在这个范围内,java的自动装箱功能,就是把一个或多个对象的内存指向一个对象使用
当不在这个范围内,就会新new一个对象
回复 使用道具 举报
在java中,“==”是比较object的reference而不是value,自动装箱后,abcd都是Integer这个Object,因此“==”比较的是其引用。那为什么in1 == in2呢,因为在自动装箱时,java在编译的时候Integer in1 = 127;被翻译成Integer a = Integer.valueOf(100);关键就在于这个valueOf()的方法。
  1.         public static Integer valueOf(int i) {
  2.                 final int offset = -128;
  3.                 if (i >= -128 && i <= 127) {
  4.                         return IntegerCache.cache[i + offset];
  5.                 }
  6.                 return new Integer(i);
  7.         }

  8.         private static class IntegerCache {
  9.                 private IntegerCache() {
  10.                 }
  11.        
  12.                 static final Integer cache[] = new Integer[-(-128) + 127 + 1];
  13.                 static {
  14.                         for (int i = 0; i < cache.length; i++) {
  15.                                 cache = new Integer(i - 128);
  16.                         }
  17.                 }
  18.         }
复制代码

根据上面的jdk源码,java为了提高效率,IntegerCache类中有一个数字缓存了值从-128到127的Integer对象,当我们调用Integer.valueOf(int i)的时候,如果i的值是>=-128且<=127时,会直接从这个缓存中返回一个对象,否则就new一个Integer对象。
我的技术blog里面正好有一篇讲这个的,欢迎去看看
http://blog.csdn.net/u011559849/article/details/21563581
回复 使用道具 举报 2 0
您需要登录后才可以回帖 登录 | 加入黑马