3.6. Autoboxing and Unboxing
Autoboxing and unboxing are typically used for collections of primitives. Autoboxing involves the dynamic allocation of memory and initialization of an object for each primitive. Note that the overhead can often exceed the execution time of the desired operation. Unboxing involves the production of a primitive for each object.
Computationally intensive tasks using primitives, e.g., iterating through primitives in a container, should be done using arrays of primitives in preference to collections of wrapper objects.
3.6.1. Autoboxing
Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes. In this example, the prizefighter's weight of 147 is automatically converted to its corresponding wrapper class because collections store references, not primitive values.
// Create hash map of weight groups
HashMap<String, Integer> weightGroups
= new HashMap<String, Integer> ( );
weightGroups.put("welterweight", 147);
weightGroups.put("middleweight", 160);
weightGroups.put("cruiserweight", 200);
The following example shows an acceptable but not recommended use of Autoboxing:
// Establish weight allowance
Integer weightAllowanceW = 5; //improper
|
As there is no reason to force autoboxing, the above statement should be written as follows:
Integer weightAllowanceW = new Integer (5);
3.6.2. Unboxing
Unboxing is the automatic conversion of the wrapper classes to their corresponding primitive types. In this example, a reference type is retrieved from the hash map. It is automatically unboxed so that it can fit into the primitive type.
// Get the stored weight limit
int weightLimitP = weightGroups.get(middleweight);
|
The following example shows an acceptable but not recommended use of unboxing:
// Establish the weight allowance
weightLimitP = weightLimitP + weightAllowanceW;
This expression can also be equivalently written with the intValue( ) method, as shown here:
weightLimitP = weightLimitP + weightAllowanceW.intValue(
);
No comments:
Post a Comment