public class IntegerTest {
public static void main(String[] args) {
objPoolTest();
}
public static void objPoolTest() {
Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 0;
Integer i4 = new Integer(50);
Integer i5 = new Integer(50);
Integer i6 = new Integer(0);
System.out.println( (i1 == i2));//初始变量时返回缓冲池的同一对象所有true;
System.out.println( (i1 == i2 + i3));相加,拆箱。所有相等。
System.out.println( (i4 == i5));不同对象,所有不等
System.out.println( (i4 == i5 + i6)); //相加拆箱。所以相等!
}
}
true
true
false
true
/**
* 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);
}