Java Reference
In-Depth Information
Solution
Define a class using < TypeName > where the container type is declared, and TypeName where
it is used.
Discussion
Consider the very simple Stack class in Example 7-2 . (We discuss the nature and uses of
stack classes in Stack ) .
This version has been parameterized to take a type whose local name is T . This type T will be
the type of the argument of the push() method, the return type of the pop() method, and so
on. Because of this return type—more specific than the Object return type of the original
Collections—the return value from pop() does not need to be downcasted. All containers in
the Collections Framework ( java.util ) are parameterized similarly.
Example 7-2. MyStack.java
public
public class
class MyStack
MyStack < T > implements
implements SimpleStack < T > {
private
private int
int depth = 0 ;
public
public static
static final
final int
int DEFAULT_INITIAL = 10 ;
private
private T [] stack ;
public
public MyStack () {
this
this ( DEFAULT_INITIAL );
}
public
public MyStack ( int
int howBig ) {
iif ( howBig <= 0 ) {
throw
new IllegalArgumentException (
howBig + " must be positive, but was " + howBig );
throw new
}
stack = ( T []) new
new Object [ howBig ];
}
@Override
public
public boolean
boolean empty () {
return
return depth == 0 ;
}
/** push - add an element onto the stack */
@Override
public
public void
void push ( T obj ) {
Search WWH ::




Custom Search