java整数缓存,Java整数类型包装类的缓存机制

Java 5以后为优化内存占用对整数类型提供了自动装箱缓存机制,在一定范围内的整数自动装箱时生成的对象是指向缓存地址的。

注意自动装箱是通过Integer a = 10;这种方式来声明的,实际上会调用Integer.valueOf();在这个方法中,使用了缓存数组。如果是通过new Integer则每次都会新建对象。

Integer.valueOf();

/**

* Returns a {@code Integer} instance for the specified integer value.

*

* If it is not necessary to get a new {@code Integer} instance, it is

* recommended to use this method instead of the constructor, since it

* maintains a cache of instances which may result in better performance.

*

* @param i

*            the integer value to store in the instance.

* @return a {@code Integer} instance containing {@code i}.

* @since 1.5

*/

public static Integer valueOf(int i) {

return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];

}

/**

* A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing

*/

private static final Integer[] SMALL_VALUES = new Integer[256];

static {

for (int i = -128; i < 128; i++) {

SMALL_VALUES[i + 128] = new Integer(i);

}

}

测试代码:

public class Main {

public static void main(String[] args) {

//Java整数类型的类包装类的缓存机制

//Integer 自动装箱缓存范围 -128-127,可以通过 JVM 的启动参数 -XX:AutoBoxCacheMax=size 修改最大范围

Integer i1 = 127, i2 = 127;

System.out.println("i1==i2 " + (i1 == i2));

Integer i3 = 128, i4 = 128;

System.out.println("i4==i4 " + (i3 == i4));

// Character 自动装箱缓存范围 0-127

Character c1 = 127, c2 = 127;

System.out.println("c1==c2 " + (c1 == c2));

Character c3 = 128, c4 = 128;

System.out.println("c3==c4 " + (c3 == c4));

// Byte,Short,Long 有固定范围: -128 到 127

Long l1 = 127L, l2 = 127L;

System.out.println("l1==l2 " + (l1 == l2));

Long l3 = 128L, l4 = 128L;

System.out.println("l3==l4 " + (l3 == l4));

}

}

运行结果:

08791f958aa39d931fb459f7326f2705.png

参考资料:

http://www.tuicool.com/articles/AJFzEra

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值