毕业刚工作的时候,带我的小师傅给我说判断相等使用equals不要使用==,第一次写java的我照办了,但是不清楚为什么,之后还是决定真正了解一下java本身。于是开始看jdk源码。这里以Integer为例
equal
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
可以看到equals方式是对Integer的内容进行比较,用equals确实没有问题
那==是怎么回事呢?
一般都知道在各类语言中都来比对地址的,不让用我可以理解,但是为什么在项目中又看到有人用到呢?并且也没什么问题?地址是一样的?不过不应该啊,于是开始看Integer在java中赋值过程是怎么回事
java中Integer的赋值过程。
Integer integer1=123;
看字节码文件发现
可以看到Integer是调用了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);
}
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() {}
}
点开源码一下就了解怎么回事了,这不就是工作中缓存热点数据么。
原来它会在内存中缓存一份热点数据-127-128,赋值过来如果在这个范围内直接返回对应坐标下的对象。所以说我们的数据只要在设置的范围内,我们拿到的都是一个对象,地址当然相同,用==判断一定也没有问题。
又大概看了一下其他基础类型的包装类Long、Byte、Short都是类似设计,
Double、float直接创建新对象