5.1.自动装箱

\(5.1\)自动装箱

1.自动装箱与解包

  当我们实例化一个泛型对象时,我们需要指定其具体的类型,例如LinkedListDeque<Integer>。对于\(Java\)\(8\)种基本类型,我们使用相应的引用类型,这些引用类型被称为包装类(\(wrapper\;classes\)):

  由引用类型转换到基本类型,我们不需要执行额外的操作。例如,我们可以直接写如下程序:

1
2
3
4
5
6
7
8
public class BasicArrayList {
public static void main(String[] args) {
ArrayList<Integer> L = new ArrayList<Integer>();
L.add(5);
L.add(6);
int first = L.get(0);
}
}

  而不必写成如下繁琐的形式:

1
2
3
4
5
6
7
8
9
10
public class BasicArrayList {
public static void main(String[] args) {
ArrayList<Integer> L = new ArrayList<Integer>();
L.add(new Integer(5));
L.add(new Integer(6));

/* Use the Integer.valueOf method to convert to int */
int first = L.get(0).valueOf();
}
}

  这是因为\(Java\)会自动“装箱”(\(autobox\))与“解包”(\(unbox\))基本类型与引用类型。因此,下面的程序都是正确的:

1
2
3
4
5
6
public static void blah(Integer x) {
System.out.println(x);
}

int x = 20;
blah(x);
1
2
3
4
5
6
public static void blahPrimitive(int x) {
System.out.println(x);
}

Integer x = new Integer(20);
blahPrimitive(x);

  不过需要注意,数组不能自动装箱或解包。

2.类型扩展

  当需要的时候,\(Java\)会自动扩展一个初始类型的范围,例如:

1
2
3
4
5
6
public static void blahDouble(double x) {
System.out.println(“double: “ + x);
}

int x = 20;
blahDouble(x);

  是正确的,但:

1
2
3
4
5
6
public static void blahInt(int x) {
System.out.println(“int: “ + x);
}

double x = 20;
blahInt(x);

  是错误的,因为\(int\)的范围小于\(double\),不能扩展到比自己更大的集合中。此时必须使用类型铸造:

1
2
double x = 20;
blahInt((int) x);