Integerキャッシュプール

1698 ワード

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));    // 。 !
        
    }
}

  truetruefalsetrue
/**
     * 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);
    }