Java Integer及int装箱拆箱对比
示例代码:
class BoxIntInteger {
public static void main(String[] args) {
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a == b;
boolean equal2 = a.equals(b);
System.out.println(equal1);
System.out.println(equal2);
}
}
反编译字节码:
public static void main(String args[])
{
Integer a = new Integer(10111);
int b = 10111;
boolean equal1 = a.intValue() == b;
boolean equal2 = a.equals(Integer.valueOf(b));
System.out.println(equal1);
System.out.println(equal2);
}
1:可以看出对于Integer与int使用==比较大小的话,优先Integer拆箱。
2: 如果使用equals比较大小的话,则int装箱。
提示:对于Integer与int之间大小比较优先使用equals比较,否则容易出现空指针,例如:
Integer c= null;
System.out.println(c==1);
原因:由于Integer需要调用intValue进行拆箱,因而空指针。
Integer与Integer必须使用equals方法比较,这个就不必解释了。但是通常我们可以看先Integer与Integer之间使用==也可以正确比较,原因是:Integer对于-128到127之间的数字在缓存中拿,不是创建新对象。
缓存获取数据源码:java.lang.Integer#valueOf(int)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
SpringBoot条件注解之@ConditionalOnClass等注解的使用场景分析
文章详细介绍了SpringBoot中条件注解的体系,包括基本概念、@ConditionalOnClass等常用注解的工作原理和使用场景,文章还探讨了条件注解的组合使用、实战应用以及最佳实践,帮助开发者更好地理解和应用条件注解,实现更灵活和智能的应用配置,感兴趣的朋友一起看看吧2025-03-03
springboot项目打包发布部署的过程及jar和war的区别
Spring Boot使用了内嵌容器,因此它的部署方式也变得非常简单灵活,可以将Spring Boot项目打包成JAR包来独立运行,Spring Boot项目既可以生成WAR包发布,也可以生成JAR包发布,那么它们有什么区别呢2022-11-11
Spring两种任务调度Scheduled和Async的区别和应用场景详解
在现代应用程序中,任务调度是一个非常普遍的需求,Spring框架提供了两种主要的方式来实现任务调度:Scheduled 和 Async,在这篇文章中,我们将详细介绍这两种方式的区别和应用场景,需要的朋友可以参考下2024-12-12


最新评论