int和Integer
来源:互联网 发布:java 在类中定义接口 编辑:程序博客网 时间:2024/05/21 21:01
看下面这段代码:
public class newTest { public static void main(String[] args){ Integer t1 = 59;//回去Integer缓存里面取找,找不着会创建一个新的Integer对象 int t2 = 59;//基本类型,与Integer Integer t3 = Integer.valueOf(59);//取缓存里面寻找 Integer t4 = new Integer(59);//创建新的Integer对象 System.out.println(t1 == t2); // true System.out.println(t1 == t3); // true System.out.println(t3 == t4); // false System.out.println(t1 == t4); // false System.out.println(t2 == t4); // true }}
在上面的代码中,其实t1和t3是等价的,因为t1反编译结果Integer t1 = Integer.valueOf(59);
那么,来看看valueOf这个函数,如下面所示:
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); }
从上面可以看出,当数字在-128~127的时候,就会从这个Cache里面找,当数字不在这个区间内,会返回一个新的Integer对象。既然如此,那再看看IntegerCache这个类
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)); } 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类型的cache数组,并且缓存了K个Integer对象。而当Integer与int相比较的时候,反编译得到的是:t1.intValue() = t2;
再看看intValue(): public int intValue() {
return value;
}
返回的是public Integer(int value) {
this.value = value;
}
构造函数带入的int值。
所以,我们知道了在-128~127之间的数相比较返回都应该为true,t4因为是新创建的对象,在Integer缓存中找不着,与缓存中的Integer对象进行比较所以为false。
阅读全文
0 0
- int 和 integer
- int 和 Integer 解读
- int 和Integer
- int和integer
- int 和 integer 比较
- int和integer
- int和Integer区别
- int和Integer
- Java Integer和int
- Integer和int
- int、Integer和IntHolder
- Integer和int
- int 和 integer 区别
- int 和 Integer
- int和Integer区别
- int 和 Integer 区别
- Integer和int相关
- int和Integer学习
- 跟随 Google 工程师学习前端开发,是种怎样的体验?
- 程序员要知道的英语词汇
- HTML编码规范
- 美国硅谷里的中国码农!
- 浅谈程序员的英语学习
- int和Integer
- 北大高材生被华为辞退:用不用你,与能力无关!
- 什么叫互联网思维模式?
- 编译错误:Could not get unknown property 'release' for SigningConfig container
- 实验3:栈和队列的基本操作实现及其应用——顺序栈和链栈
- 内核漏洞进击之旅——Dark Composition Exploitation Case Study
- 【福利】3980元的web前端视频教程限量领取!!!
- 67 个拯救前端开发者的工具、库和资源
- 前端程序员需要知道的7种新型的CSS长度单位