自动装箱与拆箱是编译器语法糖,本质调用valueOf和intValue方法,需警惕性能损耗、循环中频繁创建对象及null导致的NullPointerException,且Integer缓存-128到127,应使用equals比较对象。

Java的自动装箱与拆箱本质上是编译器提供的语法糖,方便了基本类型和它们对应的包装类型之间的转换。但如果不理解其背后的机制,很容易掉入性能陷阱,或者遇到一些意想不到的NullPointerException。
自动装箱就是将基本类型自动转换为对应的包装类型,例如将
int
Integer
Integer i = 10; // 自动装箱 int j = i; // 自动拆箱
这段代码看起来非常简洁,但实际上,
Integer i = 10;
Integer i = Integer.valueOf(10);
int j = i;
int j = i.intValue();
Integer.valueOf()
频繁的装箱拆箱会带来性能损耗。尤其是在循环中进行大量的装箱拆箱操作,会创建大量的临时对象,增加GC的压力。
立即学习“Java免费学习笔记(深入)”;
long sum = 0L;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
sum += i; // i 会被自动装箱成Long,然后拆箱成long
}
System.out.println(sum);上面的代码看似简单,但效率很低。每次循环,
i
Long
Long
Long
long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);由于自动拆箱可能会导致
NullPointerException
null
Integer i = null; int j = i; // 抛出NullPointerException
上面的代码中,
i
null
int j = i;
null
NullPointerException
避免这种错误的方法是在使用包装类型时,始终进行
null
Integer i = null; int j = (i != null) ? i : 0; // 安全的拆箱
或者使用
Optional
Integer i = null; int j = Optional.ofNullable(i).orElse(0);
Integer
Integer
==
Integer
true
false
Integer a = 100; Integer b = 100; System.out.println(a == b); // true Integer c = 200; Integer d = 200; System.out.println(c == d); // false
上面的代码中,
a == b
true
a
b
c == d
false
c
d
因此,在比较两个
Integer
equals()
==
Integer a = 200; Integer b = 200; System.out.println(a.equals(b)); // true
以上就是深入理解Java的自动装箱与拆箱机制及其潜在问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号