自动装箱的陷阱(轉載)

轉載地址:http://lizhensan.iteye.com/blog/1689176

 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())));

 

 

 

 

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

 

 

源代码

 

Java代码  
  1. public static Integer valueOf(int i) {  
  2.     final int offset = 128;  
  3.     if (i >= -128 && i <= 127) { // must cache   
  4.         return IntegerCache.cache[i + offset];  
  5.     }  
  6.         return new Integer(i);  
  7.     }  

 

Java代码  
    1. static final Integer cache[] = new Integer[-(-128) + 127 + 1];  
    2.   
    3.     static {  
    4.         for(int i = 0; i < cache.length; i++)  
    5.         cache[i] = new Integer(i - 128);  
    6.     }  
    7.     } 
posted @ 2015-02-02 09:53  青青子衿J  阅读(93)  评论(0)    收藏  举报