Java Reference
In-Depth Information
adapter class is typically used when the interface of a class is not exactly what
is needed, and provides a wrapping effect, while changing the interface.
In Java, we have already seen that although every reference type is com-
patible with
Object
, the eight primitive types are not. As a result, Java provides
a wrapper class for each of the eight primitive types. For instance, the wrapper
for the
int
type is
Integer
. Each wrapper object is
immutable
(meaning its
state can never change), stores one primitive value that is set when the object
is constructed, and provides a method to retrieve the value. The wrapper
classes also contain a host of static utility methods.
As an example, Figure 4.25 shows how we can use the Java 5
ArrayList
to
store integers. Note carefully that we cannot use
ArrayList<int>
.
4.6.3
autoboxing/unboxing
The code in Figure 4.25 is annoying to write because using the wrapper
class requires creation of an
Integer
object prior to the call to
add
, and then
the extraction of the
int
value from the
Integer
, using the
intValue
method.
Prior to Java 1.4, this is required because if an
int
is passed in a place
where an
Integer
object is required, the compiler will generate an error
message, and if the result of an
Integer
object is assigned to an
int
, the
compiler will generate an error message. This resulting code in Figure 4.25
accurately reflects the distinction between primitive types and reference
types, yet, it does not cleanly express the programmer's intent of storing
int
s in the collection.
Java 5 rectifies this situation. If an
int
is passed in a place where an
Inte-
ger
is required, the compiler will insert a call to the
Integer
constructor behind
the scenes. This is known as auto-boxing. And if an
Integer
is passed in a
figure 4.25
An illustration of the
Integer
wrapper class
using Java 5 generic
ArrayList
1
import java.util.ArrayList;
2
3
public class BoxingDemo
4
{
5
public static void main( String [ ] args )
6
{
7
ArrayList<Integer> arr = new ArrayList<Integer>( );
8
9
arr.add( new Integer( 46 ) );
10
Integer wrapperVal = arr.get( 0 );
11
int val = wrapperVal.intValue( );
12
System.out.println( "Position 0: " + val );
13
}
14
}
Search WWH ::
Custom Search