java的自动拆装箱

在学习java的时候,遇到一个 问题,感觉有时候int 与integer是一样的。但是为什么有了int,还要发明integer.为此我研究了一下java的集装箱。官方的定义

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';
通俗一点来说就是变量类型对应着自己的类包装箱。

Primitive typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble
1.  Integer i=10;

2.  int i=10;

第一个例子自动装箱,生产出的是一个对象,该对象可以调用对应的方法。而例子2对应的是一个变量,他没有可以调用方法。

3. List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(i);

例子3表面将int 类型的数据存入integer里面。实际上是自动执行了Integer.valueOf(i)

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(Integer.valueOf(i));
将原始值(例如int)转换为相应包装器类(整数)的对象称为自动装箱。 有装箱就有拆箱。将类包装箱的对象变为变量就是拆箱。

Integer i = 10; //装箱 
int t = i; //拆箱,实际上执行了 int t = i.intValue();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值