Java Integer.valueOf()返回Integer整型对象

java中Integer.valueOf()用于返回一个Integer(整型)对象,当被处理的字符串在-128和127(包含边界)之间时,返回的对象是预先缓存的。

定义

Integer valueOf(int i) 返回一个表示指定的int值的 Integer 实例。
Integer valueOf(String s) 返回保存指定的String的值的 Integer 对象。
Integer valueOf(String s, int radix)

源码

public static Integer valueOf(int i) {
	assert IntegerCache.high>= 127;
	if (i >= IntegerCache.low&& i <= IntegerCache.high)
		return IntegerCache.cache[i+ (-IntegerCache.low)];
	return new Integer(i); 
}
//静态缓存类
private static class IntegerCache {
	static final int low = -128;
	static final int high;
	static final Integer cache[];
	static {  //静态代码块
		// high value may be configured by property
		int h = 127;
		String integerCacheHighPropValue =
			sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
		if (integerCacheHighPropValue != null) {
			int i = parseInt(integerCacheHighPropValue);
			i = Math.max(i, 127);
			// Maximum array size is Integer.MAX_VALUE
			h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
		}
		high = h;

		cache = new Integer[(high - low) + 1];
		int j = low;
		for(int k = 0; k < cache.length; k++)
			cache[k] = new Integer(j++);
	}
	private IntegerCache() {}
}

实例

public class IntegerValueOfDemo {
    public static void main(String[] args) {
	System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
	System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
	System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
    }
}
输出
true
false
true

1. valueOf中127在-128到127之间对象会被缓存,因此生成了127的Integer后再次引用时候,读取的对象是同一个,因此相同。

2. 被处理的字符串128不在-128到127之间,因此会生成2个Integer对象进行对比,而“==”需要地址也必须相同,因此不同,如果用Integer.equals比较值,则相同。

3. Integer.parseInt返回的是int基本类型,“==”比较的时候只是进行值比较,因此相同。

public class IntegerValueOfDemo {
    public static void main(String[] args) {
	int i02=59;                         //这是一个基本类型,存储在栈中。 
	Integer i03 =Integer.valueOf(59);    //因为 IntegerCache 中已经存在此对象,所以,直接返回引用。 
	Integer i04 = new Integer(59) ;     //直接创建一个新的对象。 
	System.out.println(i01== i02);       //true。i01是 Integer 对象,i02是int ,这里比较的不是地址,而是值。Integer 会自动拆箱成int ,然后进行值的比较。
	System.out.println(i01== i03);       //true。因为 i03 返回的是i01的引用
	System.out.println(i03==i04);        //false。因为 i04 是重新创建的对象,所以 i03,i04 是指向不同的对象 
	System.out.println(i02== i04);       //true。因为 i02 是基本类型,所以此时 i04 会自动拆箱,进行值比较
    }
}

Integer.valueOf()是很高效的,但是需要注意的就是被处理的字符串是不是在-128到127之间,如果在的话会直接返回上一个Integer的引用;如果不在的话则会重新创建的Integer对象。