手记

IntegerExt 常量池理解, 参考源码编写

public class IntegerExt {
    private int i;
    private IntegerExt(int i) {
        this.i = i;
    }
    public int toIntValue() {
        return i;
    }
    public static void main(String[] args) {
        IntegerExt i1 = IntegerExt.getInstance(1);
        IntegerExt i2 = IntegerExt.getInstance(1);
        IntegerExt i3 = IntegerExt.getInstance(1111);
        IntegerExt i4 = IntegerExt.getInstance(1111);
        System.out.println(i1 == i2);
        System.out.println(i1.equals(i2));
        System.out.println(i3 == i4);
        System.out.println(i3.equals(i4));
    }
    public static IntegerExt getInstance(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high) {
            return IntegerCache.cache[i];
        }
        return new IntegerExt(i);
    }
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof IntegerExt) {
            return i == ((IntegerExt) obj).toIntValue();
        }
        return false;
    }
    private static class IntegerCache {
        static final int low = -128;
        static final int high = 127;
        static final IntegerExt[] cache;
        static {
            cache = new IntegerExt[(high - low) + 1];
            int j = low;
            for (int k = 0; k < cache.length; k++)
                cache[k] = new IntegerExt(j++);
        }
    }
}
1人推荐
随时随地看视频
慕课网APP