博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
装箱 拆箱
阅读量:5231 次
发布时间:2019-06-14

本文共 4345 字,大约阅读时间需要 14 分钟。

http://jzinfo.iteye.com/blog/450590(这个写的很不错)

所谓装箱,就是把基本类型用它们相对应的引用类型包起来,使它们可以具有对象的特质,如我们可以把int型包装成Integer类的对象,或者把double包装成Double,等等。

所谓拆箱,就是跟装箱的方向相反,将Integer及Double这样的引用类型的对象重新简化为值类型的数据。

 

在官网上查看一下定义:http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Autoboxing and Unboxing

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';

 

The rest of the examples in this section use generics. If you are not yet familiar with the syntax of generics, see the lesson.

Consider the following code:

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

 

Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:

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

 

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Consider the following method:

public static int sumEven(List
li) { int sum = 0; for (Integer i: li) if (i % 2 == 0) sum += i; return sum;}

 

Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime:

public static int sumEven(List
li) { int sum = 0; for (Integer i : li) if (i.intValue() % 2 == 0) sum += i.intValue(); return sum;}

 

Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

The example shows how this works:

import java.util.ArrayList;import java.util.List;public class Unboxing {    public static void main(String[] args) {        Integer i = new Integer(-8);        // 1. Unboxing through method invocation        int absVal = absoluteValue(i);        System.out.println("absolute value of " + i + " = " + absVal);        List
ld = new ArrayList<>(); ld.add(3.1416); // Π is autoboxed through method invocation. // 2. Unboxing through assignment double pi = ld.get(0); System.out.println("pi = " + pi); } public static int absoluteValue(int i) { return (i < 0) ? -i : i; }}

 

The program prints the following:

absolute value of -8 = 8pi = 3.1416

 

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing:

Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double

 

《Effective Java》中文版第2版第49条中有说到装箱拆箱的注意事项

比如说

1 public class Test {2     static Integer i;3     public static void main(String[] args) throws Exception {4         // TODO Auto-generated method stub5         if(i==1){6             System.out.println("Hello world");7         }8     }9 }

结果,空指针异常

Exception in thread "main" java.lang.NullPointerException    at Test.main(Test.java:6)

更详细的参看那本书吧

 

 

转载于:https://www.cnblogs.com/crane-practice/p/3673778.html

你可能感兴趣的文章
Python图像处理库PIL中图像格式转换
查看>>
hdu4370 dijkstra矩阵转单向边最短路矩阵+自环闭环
查看>>
Java学习笔记(2)
查看>>
查找文件工具find
查看>>
ios8以后,使用UIAlertViw时pop/push页面后,键盘闪一下的问题
查看>>
SQL之检索数据(select语句)
查看>>
[SDOI2015]排序 题解 (搜索)
查看>>
异 常
查看>>
快捷套取单色图片
查看>>
.NET-使用NPOI组件将数据导出Excel-通用方法
查看>>
团队作业8--版本说明
查看>>
数据库还原
查看>>
GDUFE ACM-1159
查看>>
HDU3686 Traffic Real Time Query
查看>>
js高德地图手机定位
查看>>
bzoj3028:食物
查看>>
Linux用户及文件管理
查看>>
pat1067 在离散数学中置换群思想上可用并查集和递归两种方法求解问题
查看>>
Linux命令----shell
查看>>
HDU 4348 To the moon 可持久化线段树
查看>>