今天看了一篇博客,问:为什么1000==
1000返回false,100==
100返回true?以我小白的眼光去看,这类型要是int的话,不是都应该为true吗?然后我就把这文章的标题截图发到了我的技术群里。有大佬立马站出来说了,这是使用int的包装类Integer,也就是这样:
public static void main(String[] args) {
Integer a = 1000, b = 1000;
System.out.println(a == b); false
Integer c = 100, d = 100;
System.out.println(c == d); true
}
文章内部也有相应的解释,但是我看着感觉还是有点绕,毕竟基础不是很好。于是大佬给我解释了一番。以下是大佬的原话:
其实这里是个语法糖。其实正常情况Integer类型与int是不可能相等的,一个是对象类型(Integer ),一个是基础数据类型(int)。只是Java搞了自动装箱和拆箱机制,会将int转换成Integer,反之亦然。但是转换时正常情况下,装箱与拆箱的对象的内存地址应该是不同的,应该仍然不等才对,但是JVM让对应的-128~127的装箱对象都缓存起来了,这意味着每次装箱在这个范围的,直接从缓存取,不会new,通过这个trick让其相等 但是超出这个范围的默认还是一般原理就不相等了
这样说的话是不是就很好理解了,另一位大佬还补充了一点。这一切的前提都是在未改变jvm启动参数的情况下
是这样的情况。
后来经过对Integer的源码进行了观察,以下是关于IntegerCache的代码:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// 高值可以通过属性配置
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// 最大数组大小是Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
//如果属性不能被解析为int型,忽略它。
}
}
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() {}
}
总结:IntegerCache 默认的缓存范围是-128到+127,且高值(也就是+127)可改变,但改变的值最低不可低于127,最高不可高于Integer的MAX_VALUE。
有了这次的经验,相信这个技术点以后都会牢牢的记住了。
此处鸣谢给我耐心解释的大佬: 周林、张健
今天充实了,开心!