在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
}
}