关于Integer的深度分析以及注意点

 

  在Integer中valueOf()和创建独享Integer的区别以及关系:

 

Integer类源代码如下:


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

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

    /**
     * Returns a <tt>Integer</tt> instance representing the specified
     * <tt>int</tt> value.
     * If a new <tt>Integer</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Integer(int)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @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);
    }

 

  

package com.easyway.commons.ispace.dev.lang.objects;


/**
 * 关于java中一些疑惑问题的以及分析
 * 
 * @author  longgangbai
 * @date 2010-5-10
 * @version 1.0
 * @since JDK6.0
 */
public class JavaQuestion {
	
	
	/**
	 * 在JDK1.5的基本类库中,对一些不可变类,如Integer类做了优化,它具有一个实例缓存,用来存放程序中经常使用的Integer实例。
	 * 如Integer中valueOf()方法。
	 * 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);
     *	}
	 * 在i在-128和127之间,第一次调用时创建Integer对象,非第一次从缓存中获取数据。
	 * 由此可见在程序中采用value()静态方法可以提供效率。
	 * 故在i不再-128到127之间时Integer.valueOf相等于new Integer()对象。
	 */
	public static void main(String[] args) {
		
		Integer a=Integer.valueOf(2);
		Integer b=Integer.valueOf(2);
		Integer c= new Integer(2);
		Integer d=new Integer(2);
		Integer aa=Integer.valueOf(234);
		Integer bb=Integer.valueOf(234);
		
		Integer cc= new Integer(234);
		Integer dd=new Integer(234);
		
		
		System.out.println("(a==b) ? "+(a==b));
		System.out.println("(c==d) ? "+(c==d));
		System.out.println("(aa==bb) ? "+(aa==bb));
		System.out.println("(cc==dd) ? "+(cc==dd));
		//输出结果如下 :
		//      (a==b) ? true
		//      (c==d) ? false
		//  	(aa==bb) ? false
		//		(cc==dd) ? false
		//      (cc==aa) ? false
	}
	

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值