如果你在Java1.5下进行过编程的话,你一定不会陌生这一点,你不能直接地向集合(Collections)中放入原始类型值,因为集合只接收对象。通常这种情况下你的做法是,将这些原始类型的值转换成对象,然后将这些转换的对象放入集合中。使用Integer,Double,Boolean等这些类我们可以将原始类型值转换成对应的对象,但是从某些程度可能使得代码不是那么简洁精炼。为了让代码简练,Java 1.5引入了具有在原始类型和对象类型自动转换的装箱和拆箱机制。但是自动装箱和拆箱并非完美,在使用时需要有一些注意事项,如果没有搞明白自动装箱和拆箱,可能会引起难以察觉的bug。
本文将介绍,什么是自动装箱和拆箱,自动装箱和拆箱发生在什么时候,以及要注意的事项。
ArrayList<Integer> intList = new ArrayList<Integer>(); intList.add(1); //autoboxing - primitive to object intList.add(2); //autoboxing ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>(); intLocal.set(4); //autoboxing int number = intList.get(0); // unboxing int local = intLocal.get(); // unboxing in Java
//before autoboxing Integer iObject = Integer.valueOf(3); Int iPrimitive = iObject.intValue() //after java5 Integer iObject = 3; //autobxing - primitive to wrapper conversion int iPrimitive = iObject; //unboxing - object to primitive conversion
ublic static Integer show(Integer iParam){ System.out.println("autoboxing example - method invocation i: " + iParam); return iParam; } //autoboxing and unboxing in method invocation show(3); //autoboxing int result = show(3); //unboxing because return type of method is Intege
Integer sum = 0; for(int i=1000; i<5000; i++){ sum+=i; }
sum = sum.intValue() + i; Integer sum = new Integer(result);
public void test(int num){ System.out.println("method with primitive argument"); } public void test(Integer num){ System.out.println("method with wrapper argument"); } //calling overloaded method AutoboxingTest autoTest = new AutoboxingTest(); int value = 3; autoTest.test(value); //no autoboxing Integer iValue = value; autoTest.test(iValue); //no autoboxing Output: method with primitive argument method with wrapper argument
public class AutoboxingTest { public static void main(String args[]) { // Example 1: == comparison pure primitive – no autoboxing int i1 = 1; int i2 = 1; System.out.println("i1==i2 : " + (i1 == i2)); // true // Example 2: equality operator mixing object and primitive Integer num1 = 1; // autoboxing int num2 = 1; System.out.println("num1 == num2 : " + (num1 == num2)); // true // Example 3: special case - arises due to autoboxing in Java Integer obj1 = 1; // autoboxing will call Integer.valueOf() Integer obj2 = 1; // same call to Integer.valueOf() will return same // cached Object System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true // Example 4: equality operator - pure object comparison Integer one = new Integer(1); // no autoboxing Integer anotherOne = new Integer(1); System.out.println("one == anotherOne : " + (one == anotherOne)); // false } } Output: i1==i2 : true num1 == num2 : true obj1 == obj2 : true one == anotherOne : false
private static Integer count; //NullPointerException on unboxing if( count <= 0){ System.out.println("Count is not started yet"); }