概述
首先我们应该明确包装类型使用 “==” 进行判断是否相等,比较的是对象的引用值是否相等,如果是相同的对象,那肯定是相等。
那么为什么会出现上面的情况呢,理论上要么全部为 true,要么全部为 false 。查看源码就知道了:
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;
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() {}
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
通过查看源码,我们发现Integer有缓存机制,缓存了[-128,127],通过vlueOf()这个方法,我们可以发现若值在-128到127范围内,就可以直接从缓存中取出。而剩余的为什么是false,因为他们都超过了缓存的那个范围,就建了个新对象。
另外基本类型和包装类型存在自动装箱和自动拆箱
类似的:Long也存在这种缓存机制
如:
Integer total = 1;
执行上面那句代码的时候,系统为我们执行了:
Integer total = Integer.valueOf(1);
最后
以上就是唠叨小刺猬为你收集整理的Integer包装类型时,使用 “==”判断,不相等的全部内容,希望文章能够帮你解决Integer包装类型时,使用 “==”判断,不相等所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复