继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

car
关注TA
已关注
手记 83
粉丝 56
获赞 363
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++);
        }
    }
}
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP