Java中Integer

本文探讨了Java中Integer对象的缓存机制,特别是-128到127之间的整数如何被缓存,以及这如何影响Integer对象的比较。通过示例代码解释了Integer.valueOf方法的工作原理,并讨论了在进行对象比较时需要注意的问题。

public class ConstantPool { public static void main(String[] args) { Integer integer1=100; Integer integer2=100; System.out.println(integer1==integer2); //Integer i=100; 编译器会自动将int类型常数100包装成Interger,采用的是Integer.valueOf(100); 这个方法。 Integer integer3=200; Integer integer4=Integer.valueOf(200); System.out.println(integer3==integer4); } }

输出的结果是:

true

false

从java的源代码中就可以找到原因:

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

private static class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128; // high value may be configured by property int h = 127; if (integerCacheHighPropValue != null) { // Use Long.decode here to avoid invoking methods that // require Integer's autoboxing cache to be initialized int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - -low); } 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() {} }

java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);,对-128~127这256个值做了缓存放到IntegerCache做了缓存,对于上一次已经创建的,再使用的时候就不会再创建了。

但是对于如下的需要注意:

Integer integer5=100; Integer integer6=Integer.valueOf(100); integer5++; System.out.println(integer5==integer6);

返回:false

是因为a++的时候是创建了另外一个对象

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值