Java Reference
In-Depth Information
figure 4.22
A generic MemoryCell
class (pre-Java 5)
1 // MemoryCell class
2 // Object read( ) --> Returns the stored value
3 // void write( Object x ) --> x is stored
4
5 public class MemoryCell
6 {
7 // Public methods
8 public Object read( ) { return storedValue; }
9 public void write( Object x ) { storedValue = x; }
10
11 // Private internal data representation
12 private Object storedValue;
13 }
figure 4.23
Using the generic
MemoryCell class
(pre-Java 5)
1 public class TestMemoryCell
2 {
3 public static void main( String [ ] args )
4 {
5 MemoryCell m = new MemoryCell( );
6
7 m.write( "37" );
8 String val = (String) m.read( );
9 System.out.println( "Contents are: " + val );
10 }
11 }
MemoryCell is a fairly small example. A larger example that is typical of
generic code reuse, Figure 4.24 shows a simplified generic ArrayList class as
it would be written before Java 5; the online code fills in some additional
methods.
4.6.2 wrappers for primitive types
When we implement algorithms, often we run into a language typing prob-
lem: We have an object of one type, but the language syntax requires an object
of a different type.
This technique illustrates the basic theme of a wrapper class . One typical
use is to store a primitive type, and add operations that the primitive type
either does not support or does not support correctly. A second example was
seen in the I/O system, in which a wrapper stores a reference to an object and
forwards requests to the object, embellishing the result somehow (for
instance, with buffering or compression). A similar concept is an adapter
class (in fact, wrapper and adapter are often used interchangeably). An
A wrapper class
stores an entity
(the wrapee) and
adds operations
that the original
type does not sup-
port correctly. An
adapter class is
used when the
interface of a class
is not exactly what
is needed.
 
Search WWH ::




Custom Search