当前位置:网站首页>自动装箱与拆箱了解吗?原理是什么?
自动装箱与拆箱了解吗?原理是什么?
2022-07-03 09:15:00 【look-word】
自动装箱与拆箱了解吗?原理是什么?
什么是自动拆装箱?
- 装箱:将基本类型用它们对应的引用类型包装起来;
- 拆箱:将包装类型转换为基本数据类型;
举例:
Integer i = 10; //装箱
int n = i; //拆箱
字节码文件
L1
LINENUMBER 8 L1
ALOAD 0
BIPUSH 10
INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
PUTFIELD AutoBoxTest.i : Ljava/lang/Integer;
L2
LINENUMBER 9 L2
ALOAD 0
ALOAD 0
GETFIELD AutoBoxTest.i : Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue ()I
PUTFIELD AutoBoxTest.n : I
RETURN
从字节码中,我们发现装箱其实就是调用了 包装类的valueOf()方法,拆箱其实就是调用了 xxxValue()方法。
因此,
Integer i = 10等价于Integer i = Integer.valueOf(10)int n = i等价于int n = i.intValue();
注意:如果频繁拆装箱的话,也会严重影响系统的性能。我们应该尽量避免不必要的拆装箱操作
private static long sum() {
// 应该使用 long 而不是 Long
Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++)
sum += i;
return sum;
}
边栏推荐
- Vector processor 9_ Basic multilevel interconnection network
- Leetcode daily question (2109. adding spaces to a string)
- Programming ideas are more important than anything, not more than who can use several functions, but more than the understanding of the program
- MySQL Data Definition Language DDL common commands
- 新系列单片机还延续了STM32产品家族的低电压和节能两大优势
- JMX、MBean、MXBean、MBeanServer 入门
- Uncle Wang's blog directory [constantly updating]
- Leetcode daily question (1856. maximum subarray min product)
- STM32 external interrupt experiment
- Find all possible recipes from given supplies
猜你喜欢
随机推荐
Fundamentals of Electronic Technology (III)_ Integrated operational amplifier and its application__ Basic arithmetic circuit
Project cost management__ Cost management technology__ Article 8 performance review
Leetcode daily question (985. sum of even numbers after queries)
Nr-prach: access scenario and access process
应用最广泛的8位单片机当然也是初学者们最容易上手学习的单片机
Introduction to chromium embedded framework (CEF)
Code word in NR
Project cost management__ Plan value_ Earned value_ Relationship among actual cost and Countermeasures
Project cost management__ Cost management technology__ Article 7 completion performance index (tcpi)
Leetcode daily question (2232. minimize result by addressing parents to expression)
STM32 port multiplexing and remapping
Directory and switching operation in file system
[CSDN]C1训练题解析_第四部分_Web进阶
我想各位朋友都应该知道学习的基本规律就是:从易到难
Vector processor 9_ Basic multilevel interconnection network
[CSDN] C1 training problem analysis_ Part III_ JS Foundation
Leetcode daily question (2109. adding spaces to a string)
Leetcode daily question (931. minimum falling path sum)
MySQL的简单使用(增删改查)
【22毕业季】我是毕业生yo~


![[CSDN]C1训练题解析_第二部分_Web基础](/img/91/72cdea3eb3f61315595330d2c9016d.png)






