`
lizhensan
  • 浏览: 369678 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java 语法糖-自动装箱的陷阱

    博客分类:
  • java
 
阅读更多

  public static void main(String[] args) {
  Integer a=1;
  Integer b=2;
  Integer c=3;
  Integer d=3;
  Integer e=321;
  Integer f=321;
  Long g=3L;
  System.out.println(c==d);true
  System.out.println(e==f);false
  System.out.println(c==(a+b));true
  System.out.println(c.equals(a+b));true
  System.out.println(g==(a+b));true
  System.out.println(g.equals(a+b));false
 }
}



反编译的代码

 Integer a = Integer.valueOf(1);
    Integer b = Integer.valueOf(2);
    Integer c = Integer.valueOf(3);
    Integer d = Integer.valueOf(3);
    Integer e = Integer.valueOf(321);
    Integer f = Integer.valueOf(321);
    Long g = Long.valueOf(3L);
    System.out.println(c == d);
    System.out.println(e == f);
    System.out.println(c.intValue() == a.intValue() + b.intValue());
    System.out.println(c.equals(Integer.valueOf(a.intValue() + b.intValue())));
    System.out.println(g.longValue() == a.intValue() + b.intValue());
    System.out.println(g.equals(Integer.valueOf(a.intValue() + b.intValue())));

 

 

 

 

在自动装箱时对于值从128127之间的值,它们被装箱为Integer对象后,会存在内存中被重用,所以范例4.6中使用==进行比较时,i1 i2实际上参考至同一个对象。如果超过了从–128127之间的值,被装箱后的Integer对象并不会被重用,即相当于每次装箱时都新建一个Integer对象,所以范例4.7使用==进行比较时,i1i2参考的是不同的对象。

 

 

源代码

 

public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }

 

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }
分享到:
评论
1 楼 sacoole 2013-10-14  

相关推荐

Global site tag (gtag.js) - Google Analytics