/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} 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.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
2. 测试
public static void main(String[] args) {
Integer a0 = 128; // 相当于Integer.valueOf(128)
Integer a = Integer.valueOf(128);
Integer b = Integer.valueOf(128);
System.out.println(a == b); // false
System.out.println(a0 == b); // false
System.out.println(128 == new Integer(128)); // Integer自动拆箱,true
Integer c = Integer.valueOf(127);
Integer d = Integer.valueOf(127);
System.out.println(c == d); // true
}
3. 总结
int类型比较,相等;
两个Integer比较, 在[-128, 127]内相等,否则不相等,因为会重新new一个对象;
清楚自动装箱(Integer a0 = 128)和自动拆箱(int a = Integer.valueOf(128));