码迷,mamicode.com
首页 > 其他好文 > 详细

Integer自动装拆箱

时间:2014-07-14 17:48:02      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   代码   div   

public static void main(String[] args) {
    Integer a1 = 1;
    Integer a2 = 1;
    Integer b1 = 127;
    Integer b2 = 127;
    Integer c1 = 128;
    Integer c2 = 128;
    Integer d1 = 321;
    Integer d2 = 321;
    System.out.println(a1 == a2);
    System.out.println(b1 == b2);
    System.out.println(c1 == c2);
    System.out.println(d1 == d2);
}

结果:

true
true
false
false

原因:

首先我们来看一下JDK源码是如何实现Integer.valueOf()方法的;

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

其中IntegerCache是Integer类中的一个内部类,其代码比较简单,如下所示:

private static class IntegerCache {
    private IntegerCache(){}

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

    static {
        for(int i = 0; i < cache.length; i++)
        cache[i] = new Integer(i - 128);
    }
}

如果传入的int在[-128~127],那就尝试看前面的缓存中有没有打过包的相同的值,如果有就直接返回,否则就创建一个Integer实例。

看到这儿之后,上面的结果就显而易见了。

 

 

 

 

 

 

 

 

 

 

 

 

 

Integer自动装拆箱,布布扣,bubuko.com

Integer自动装拆箱

标签:style   blog   color   for   代码   div   

原文地址:http://www.cnblogs.com/zjuzcj/p/3843005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!