【Java】Integer的常量池

笔试的时候遇到一个问题:

Integer i1 = 127;
Integer i2 = 127;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
System.out.println(i3==i4);
System.out.println(i3.equals(i4));

输出结果是true true false true

提到了==与equals的区别,第一反应是String。

String s  = new String("....")是分配在堆中不同位置的,==返回false。

String s = "...";  String ss = "..." 指向池中同一个空间,然会true

equals比较的是对象的值,而==比较的是对象本体(位置)。

Integer也有区别?

附上java的源码:

    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }
可以看出来 Integer 也有常量池 范围是 -128~127

所以在此范围内的 == 返回true,范围外的 范围false。(当然,equals全部返回true)

同样,Short Long 的常量池范围也是-128~127。

Boolean 也实现了常量池的功能。毕竟只有true和false两个值

Character的范围0~127

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值