Java Reference
In-Depth Information
figure 4.27
An adapter class that
changes the
MemoryCell interface
to use get and put
1 // A class for simulating a memory cell.
2 public class StorageCell
3 {
4 public Object get( )
5 { return m.read( ); }
6
7 public void put( Object x )
8 { m.write( x ); }
9
10 private MemoryCell m = new MemoryCell( );
11 }
4.6.5 using interface types for genericity
Using Object as a generic type works only if the operations that are being
performed can be expressed using only methods available in the Object
class.
Consider, for example, the problem of finding the maximum item in an
array of items. The basic code is type-independent, but it does require the
ability to compare any two objects and decide which is larger and which is
smaller. For instance, here is the basic code for finding the maximum BigInteger
in an array:
public static BigInteger findMax( BigInteger [ ] arr )
{
int maxIndex = 0;
for( int i = 1; i < arr.length; i++ )
if( arr[i].compareTo( arr[ maxIndex ] < 0 )
maxIndex = i;
return arr[ maxIndex ];
}
Finding the maximum item in an array of String , where maximum is
taken to be lexicographically (i.e. alphabetically last) is the same basic
code.
 
Search WWH ::




Custom Search