Java Integer及int装箱拆箱对比
示例代码:
classBoxIntInteger{
publicstaticvoidmain(String[]args){
Integera=newInteger(10111);
intb=10111;
booleanequal1=a==b;
booleanequal2=a.equals(b);
System.out.println(equal1);
System.out.println(equal2);
}
}
反编译字节码:
publicstaticvoidmain(Stringargs[])
{
Integera=newInteger(10111);
intb=10111;
booleanequal1=a.intValue()==b;
booleanequal2=a.equals(Integer.valueOf(b));
System.out.println(equal1);
System.out.println(equal2);
}
1:可以看出对于Integer与int使用==比较大小的话,优先Integer拆箱。
2:如果使用equals比较大小的话,则int装箱。
提示:对于Integer与int之间大小比较优先使用equals比较,否则容易出现空指针,例如:
Integerc=null;
System.out.println(c==1);
原因:由于Integer需要调用intValue进行拆箱,因而空指针。
Integer与Integer必须使用equals方法比较,这个就不必解释了。但是通常我们可以看先Integer与Integer之间使用==也可以正确比较,原因是:Integer对于-128到127之间的数字在缓存中拿,不是创建新对象。
缓存获取数据源码:java.lang.Integer#valueOf(int)
publicstaticIntegervalueOf(inti){
if(i>=IntegerCache.low&&i<=IntegerCache.high)
returnIntegerCache.cache[i+(-IntegerCache.low)];
returnnewInteger(i);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语