Autoboxing and Auto-Unboxing

In versions of Java prior to J2SE 5.0, if you wanted to insert a primitive value into a data structure that could store only Objects, you had to create a new object of the corresponding type-wrapper class, then insert this object in the collection. Similarly, if you wanted to retrieve an object of a type-wrapper class from a collection and manipulate its primitive value, you had to invoke a method on the object to obtain its corresponding primitive-type value. For example, suppose you want to add an int to an array that stores only references to Integer objects. Prior to J2SE 5.0, you would be required to "wrap" an int value in an Integer object before adding the integer to the array and to "unwrap" the int value from the Integer object to retrieve the value from the array, as in

Integer[] integerArray = new Integer[ 5 ]; // create integerArray // assign Integer 10 to integerArray[ 0 ] integerArray[ 0 ] = new Integer( 10 ); // get int value of Integer int value = integerArray[ 0 ].intValue();

Notice that the int primitive value 10 is used to initialize an Integer object. This achieves the desired result but requires extra code and is cumbersome. We then need to invoke method intValue of class Integer to obtain the int value in the Integer object.

J2SE 5.0 simplifies converting between primitive-type values and type-wrapper objects, requiring no additional code on the part of the programmer. J2SE 5.0 introduces two new conversionsthe boxing conversion and the unboxing conversion. A boxing conversion converts a value of a primitive type to an object of the corresponding type-wrapper class. An unboxing conversion converts an object of a type-wrapper class to a value of the corresponding primitive type. J2SE 5.0 allows these conversions to be performed automatically (called autoboxing and auto-unboxing). For example, the previous statements can be rewritten as

Integer[] integerArray = new Integer[ 5 ]; // create integerArray integerArray[ 0 ] = 10; // assign Integer 10 to integerArray[ 0 ] int value = integerArray[ 0 ]; // get int value of Integer

In this case, autoboxing occurs when assigning an int value (10) to integerArray[ 0 ], because integerArray stores references to Integer objects, not int primitive values. Auto-unboxing occurs when assigning integerArray[ 0 ] to int variable value, because variable value stores an int value, not a reference to an Integer object. Autoboxing and auto-unboxing also occur in control statementsthe condition of a control statement can evaluate to a primitive boolean type or a Boolean reference type. Many of this chapter's examples use these conversions to store primitive values in and retrieve them from data structures that store only references to Objects.

Категории