概述
Integer中判断是否相等的的问题
实验代码:
public class Test1 {
public static void main(String[] args) {
Integer x1 = 1;
Integer x2 = 1;
System.out.println(x1 == x2);
Integer x3 = 10;
int x4 = 10;
System.out.println(x3 == x4);
Integer x5 = 128;
Integer x6 = 128;
System.out.println(x5 == x6);
}
}
结果:
结果分析:
样例代码所对应的字节码如下图所示:
我们来看Integer中的valueOf方法
源码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这个里面出现了一个新的类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;
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() {}
}
从源码中我们可以看出,该类维护了一个Integer的数组,数组值从-128到127,如果没有则这个范围内,则会新创建一个Integer对象(从valueOf方法中可已看出)。
最后
以上就是暴躁钢笔为你收集整理的Integer中判断是否相等的的问题的全部内容,希望文章能够帮你解决Integer中判断是否相等的的问题所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复