自动装箱、自动拆箱小结

在JDK1.5之前,集合框架类只能保存对象引用, 基本类型的数据被排斥在外,如果想保存基本类型的数据,那么必须使用对应的包装类才行,比如 int 对应的包装类是 Integer 。在 Java中,这种将基本类型转为对应包装类的操作被称为装箱(boxing);将包装类转为对应基本类型的操作称为拆箱(unboxing)。装箱和拆箱的操作使我们的java代码杂乱繁琐,JDK1.5的特性之一就是自动装箱(autoboxing)和自动拆箱(auto-unboxing),为我们解决了这个问题。

示例:


package com.darkmi.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BoxingTest {
public static void main(String[] args) {
List list = new ArrayList();
//autoboxing
list.add(111);
list.add(222);
list.add(333);

//auto-unboxing
int value1 = list.get(0);
int value2 = list.get(1);
int value3 = list.get(2);
System.out.println(value1);
System.out.println(value2);
System.out.println(value3);

//~~~~~~~~~~

Map map = new HashMap();
//autoboxing
map.put(1, "aaa-value");
map.put(2, "bbb-value");
map.put(3, "ccc-value");

//auto-unboxing
String valueA = map.get(1);
String valueB = map.get(2);
String valueC = map.get(3);
System.out.println(valueA);
System.out.println(valueB);
System.out.println(valueC);

}
}

说明:

(1)通过示例可以看出,自动装箱和拆箱的最大好处就是可以忽略 int 和 Integer 之间的区别;

(2)因为Integer 可以为 null ,所以对 null 自动拆箱的话会抛出一个 NullPointerException 异常;

(3)虽然自动装箱和自动拆箱是自动完成的,但还是会有一定的性能损耗。

何时使用自动装箱和自动拆箱?

当引用类型和基本类型之间有 impedance mismatch 的时候使用,比如在集合框架类中保存数值数据的时候。对于科学计算或者对性能要求很高的数值运算则不要采用自动装箱和拆箱机制。Integer 并不能完全取代 int ,自动装箱和自动拆箱可以简化他们之间的转换,但是并不会消除他们之间的区别。

原文:

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

参考:http://download.oracle.com/javase/autoboxing.html

此条目发表在computer分类目录,贴了, , , 标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据