valueOf() 方法的作用?
官方文档里对valueOf()方法的定义如下:
Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
整理可得:
- 该方法会返回表示指定int值的缓存池中的对象,多次调用会取得同一个对象的引用。这有助于多次使用相同同一个值时减少内存消耗。
- 此方法将始终缓存固定范围内的值,**并且可能缓存此范围之外的其他值。**可以自行设置。
Java 8 中Integr包装类该方法源码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
分析源码可以知道,valueOf()使用时:
- 要调用值在缓冲池中:返回返回值中内容。
- 不在缓冲池范围内:新建对应包装类类型对象。
由其方法特性延伸的注意点:
-
所谓128陷阱,现象上看是因为:IntegerCache中内设的缓冲池值区间为**-128~127。
实际是编译器会在缓冲池范围内的基本类型自动装箱过程调用 valueOf() 方法,因此多个 实例使用自动装箱来创建并且值相同,那么就会引用相同的对象。
Integer aa=-128; Integer a=-128; System.out.println(a==aa);//true Integer b1=127; Integer b2=Integer.valueOf(127); System.out.println(b1==b2);//true
-
而不在缓冲池范围内的值则无该特性,两者指向不同的引用地址,此时使用"=="比较的是两对象的地址是否相同,而应该使用equals()方法来比较包装类的值是否相同。
Integer a1=128;
Integer a2=Integer.valueOf(128);
System.out.println(a1==a2);//false
System.out.println(a1.equals(a2));//true