Java Integer的缓存策略

在做力扣76. 最小覆盖子串的时候,有一个case总是过不去,最后没办法,试了下将Integer1==Integer2改为Integer.equals(Integer2),没想到居然过了,查了一下发现是Integer的缓存机制造成的,这种机制好处是对于[128,127]来说很常用,缓存起来效率非常高,因为不用创建新对象了,但是做题非常坑,边缘条件啊。不过以后看到引用数据类型,比较还是用equals()吧。

		Integer a = 127;
        Integer b = 127;
        System.out.println(a == b);//true
        System.out.println(a.equals(b));//true
        System.out.println(a.hashCode());//127
        System.out.println(b.hashCode());//127
        a = 128;
        b = 128;
        System.out.println(a == b);//false
        System.out.println(a.equals(b));//true
        System.out.println(a.hashCode());//128
        System.out.println(b.hashCode());//128

在 Java 5 中,为 Integer 的操作引入了一个新的特性,用来节省内存和提高性能。整型对象在内部实现中通过使用相同的对象引用实现了缓存和重用,上面的规则适用于整数区间 -128 到 +127。
Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这相当于调用 valueOf 方法

		 a = Integer.valueOf(3);//手动装箱
        b = 3;//自动装箱
        System.out.println(a == b);//true
        System.out.println(a.equals(b));//true

这种 Integer 缓存策略仅在自动装箱(autoboxing)的时候有用,使用构造器创建的 Integer 对象不能被缓存。

		a = Integer.valueOf(3);//等于a=3
        b = new Integer(3);
        System.out.println(a == b);//false
        System.out.println(a.equals(b));//true
 /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)//low=-128,high=127
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

这种缓存行为不仅适用于Integer对象。我们针对所有整数类型的类都有类似的缓存机制。

有 ByteCache 用于缓存 Byte 对象
有 ShortCache 用于缓存 Short 对象
有 LongCache 用于缓存 Long 对象
有 CharacterCache 用于缓存 Character 对象
Byte,Short,Long 有固定范围: -128 到 127。对于 Character, 范围是 0 到 127。除了 Integer 可以通过参数改变范围外,其它的都不行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值