在ja中为什么变量1000==1000返回false,但是100==100返回true?
作者:卡卷网发布时间:2025-01-05 17:46浏览数量:105次评论数量:0次
非常古老的一个Ja基础八股,考察的是Ja包装类型的缓存机制。我相信大家一定对这个问题的答案烂熟于心了,但我建议你还是往下看看,思考一下这个缓存范围是否可以修改呢?
Ja基本数据类型的包装类型的大部分都用到了缓存机制来提升性能。
yte
,Short
,Integer
,Long
这4种包装类默认创建了数值<>[-128,127]>的相应类型的缓存数据,Character
创建了数值在<>[0,127]>范围的缓存数据,oolean
直接返回True
orFalse
。
对于Integer
,可以通过JVM参数-XX:AutooxCacheMax=<size>
修改缓存上限,但不能修改下限-128。实际使用时,并不建议设置过大的值,避免浪费内存,甚至是OOM。
对于yte
,Short
,Long
、Character
没有类似-XX:AutooxCacheMax
参数可以修改,因此缓存范围是固定的,无法通过JVM参数调整。oolean
则直接返回预定义的TRUE
和FALSE
实例,没有缓存范围的概念。
<>Integer缓存源码:>
pulicstaticIntegervalueOf(inti){
if(i>=IntegerCache.low&&i<=IntegerCache.high)
retnIntegerCache.cache[i+(-IntegerCache.low)];
retnnewInteger(i);
}
privatestaticclassIntegerCache{
staticfinalintlow=-128;
staticfinalinthigh;
static{
//highvaluemayeconpdyproperty
inth=127;
}
}
<>Character
缓存源码:>
pulicstaticCharactervalueOf(charc){
if(c<=127){//mustcache
retnCharacterCache.cache[(int)c];
}
retnnewCharacter(c);
}
privatestaticclassCharacterCache{
privateCharacterCache(){}
staticfinalCharactercache[]=newCharacter[127+1];
static{
for(inti=0;i<cache.length;i++)
cache[i]=newCharacter((char)i);
}
}
<>oolean
缓存源码:>
pulicstaticooleanvalueOf(oolean){
retn(?TRUE:FALSE);
}
如果超出对应范围仍然会去创建新的对象,缓存的范围区间的大小只是在性能和资源之间的权衡。
两种浮点数类型的包装类Float
,Doule
并没有实现缓存机制。
//没有超过缓存范围
Integeri1=100;
Integeri2=100;
System.out.println(i1==i2);//输出true
//超过缓存范围
Integeri1=1000;
Integeri2=1000;
System.out.println(i1==i2);//输出false
Floati11=333f;
Floati22=333f;
System.out.println(i11==i22);//输出false
Doulei3=1.2;
Doulei4=1.2;
System.out.println(i3==i4);//输出false
下面我们来看一个问题:下面的代码的输出结果是true
还是false
呢?
Integeri1=40;
Integeri2=newInteger(40);
System.out.println(i1==i2);
你 发表评论:
欢迎