Documentation

The Java™ Tutorials
Hide TOC
Autoboxing and Unboxing自动装箱和拆箱
Trail: Learning the Java Language
Lesson: Numbers and Strings

Autoboxing and Unboxing自动装箱和拆箱

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.自动装箱是Java编译器在原语类型与其对应的对象包装器类之间进行的自动转换。For example, converting an int to an Integer, a double to a Double, and so on.例如,将int转换为Integer,将double转换为Double,等等。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 Generics (Updated) lesson.如果您还不熟悉泛型的语法,请参阅泛型(更新版)课程

Consider the following code:考虑下面的代码:

List<Integer> 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.尽管将int值作为基本类型而不是Integer对象添加到li中,但代码仍可以编译。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.因为liInteger对象的列表,而不是int值的列表,所以您可能想知道为什么Java编译器没有发出编译时错误。The compiler does not generate an error because it creates an Integer object from i and adds the object to li.编译器不会生成错误,因为它从i创建Integer对象,并将该对象添加到liThus, the compiler converts the previous code to the following at runtime:因此,编译器在运行时将以前的代码转换为以下代码:

List<Integer> 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.将原语值(例如int)转换为相应包装类(Integer)的对象称为自动装箱。The Java compiler applies autoboxing when a primitive value is:当基元值为以下值时,Java编译器将应用自动装箱:

Consider the following method:考虑以下方法:

public static int sumEven(List<Integer> 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.由于余数(%)和一元加号(+=)运算符不适用于整数对象,您可能想知道为什么Java编译器编译该方法时不会发出任何错误。The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime:编译器不会生成错误,因为它在运行时调用intValue方法将Integer转换为int

public static int sumEven(List<Integer> 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.将包装类型(Integer)的对象转换为其相应的基元(int)值称为拆箱。The Java compiler applies unboxing when an object of a wrapper class is:当包装类的对象为以下对象时,Java编译器将应用拆箱:

The Unboxing example shows how this works:Unboxing示例显示了其工作原理:

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<Double> 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 = 8
pi = 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:自动装箱和拆箱允许开发人员编写更清晰的代码,使其更易于阅读。下表列出了Java编译器用于自动装箱和拆箱的基本类型及其相应的包装类:

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

Previous page: Summary of Characters and Strings
Next page: Questions and Exercises: Characters and Strings