首页 > 其他 > 详细

关于Integer

时间:2015-11-11 23:54:27      阅读:296      评论:0      收藏:0      [点我收藏+]

如下代码

    public static void main(String[] args) {
        Integer a=1;
        Integer b=1;
        Integer c=200;
        Integer d=200;
        
        System.out.println(a==b);
        System.out.println(c==d);
    }

输出的结果为:

true
false

这种情况在版本比较低的jdk中不会出现

在编译阶段,原始类型int赋值给 Integer,自动转换Integer.valueOf(int);

而通过反编译工具查看valueOf方法。

 /*   
  * 返回一个表示指定的 int 值的 Integer 实例。如果不需要新的 Integer 实例,则   
  * 通常应优先使用该方法,而不是构造方法 Integer(int),因为该方法有可能通过   
  * 缓存经常请求的值而显著提高空间和时间性能。    
  * @param  i an <code>int</code> value.   
  * @return a <tt>Integer</tt> instance representing <tt>i</tt>.   
  * @since  1.5   
  */    
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);     
}  

可以看到对于范围在-128到127的整数,valueOf方法做了特殊处理。 
采用IntegerCache.cache[i + offset]这个方法。 
从名字,我们可以猜出这是某种缓存机制。 

进一步跟踪IntegerCache这个类,此类代码如下

/*   
  * IntegerCache内部类   
  * 其中cache[]数组用于存放从-128到127一共256个整数   
  */    
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);     
    }     
} 

 

关于Integer

原文:http://www.cnblogs.com/wqlys/p/4957711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!