您的位置首页  散文评论

ln1等于多少(ln1等于多少值)太疯狂了

Integer i=1和Integer i=200的区别大家在写代码时,可能会遇到如下的问题:Integer i=1;Integer i1=1;

ln1等于多少(ln1等于多少值)太疯狂了

 

Integer i=1和Integer i=200的区别大家在写代码时,可能会遇到如下的问题:Integer i=1;Integer i1=1;System.out.println(i==i1);//true

Integer i3=200;Integer i4=200;System.out.println(i3==i4);//false为什么是同样的自动装箱,只是两个变量赋了不同的值,结果怎么就不一样了呢?首先我们知道==是判断两个引用所指向的内存地址是否相同,而且1和200都是有序的存储在栈内存中,按理说这两个结果得到的应该都是true,为什么一个为true,一个是false呢?

原因是自动装箱时,其实默认调用的是Integer.valueOf(int i);这样的方法我们通过查看源码得知 public static Integer valueOf(int i) { //IntegerCache是一个静态内部类

if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)];

return new Integer(i); }通过对代码的分析可知,当我们自动装箱的值在一个范围,他返回的是一个cache这个缓存数组的下标的值,如果超出一个范围,那么则是new一个新的对象,那么知道,凡是new出来的都是新的对象,所以他们的内存地址肯定不同,会不会这个1在各个范围内,而我们的200不在这个范围内,所以返回了一个新的对象。

找到静态内部类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) { try { 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); } catch( NumberFormatException nfe) {

// If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1];

int j = low; //重点在这里,在程序被加载时,静态代码块被先执行,这个缓存完成了一个new对象的过程 for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {}

}所以通过代码可知,当自动装箱的值在-128~127中是,大家拿到的是缓存中提前new好的那个对象,所以其内存地址是相同的,而大于这个范围时,内存地址则不同了。所以返回的是false;

免责声明:本站所有信息均搜集自互联网,并不代表本站观点,本站不对其真实合法性负责。如有信息侵犯了您的权益,请告知,本站将立刻处理。联系QQ:1640731186