为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java
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人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
56
获赞与收藏
363

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消