在学习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 type | Wrapper class |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |
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();
Java中int与Integer的区别
本文探讨了Java中int与Integer的区别,解释了为何需要Integer类,并通过实例演示了自动装箱与拆箱的过程。
938

被折叠的 条评论
为什么被折叠?



