Integer的底层机制,和final定义的成员变量写法。

在这里插入图片描述
==比较的是地址,equals比较的是真实的值
eauals重写的方法为;

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

先看Integer的底层表示的为:

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;
        
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            VM.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

还有一点就是我们在用Final的时候,在平常定义的时候就会说必须设置初始值的,但在这里就没有设置初始值的,为什么呢?因为在这里先设置的是为静态成员变量的,他会在类加载的时候会加载,那我们就可以在同等的加载区域中给他设定初始值也是可以的,比如这里实现是在静态代码块设置初始值来实现的。
其中的Integer为一个类,在这个类中有一个静态缓存区会创建256个Integer个对象,来进行存储,挡在new的时候是在堆中创建的Integer对象的,当Integer a=1;的时候是a直接找到在Integer中已经创建的对象,-128到127的,此时上面的a,b都是指向Integer中的同一个对象,只要是new的时候就会在堆中直接创建一个新的对象,但他又不是会像String中在常量池中而是自己各自创建各自的对象,也就如下图,在这里面可以看出创建出来了,int size = (high - low) + 1;为256,archivedCache = c;表示把256个静态空间给他。
在这里插入图片描述
答案为:true false false true true true。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值