The new approach will expect a stack interface to be of the form
public interface Stack<E> {
public void push(E item);
public E pop();
...
}
where E (for element) is a type parameter. The elements
pushed onto and popped from the stack are now of type E. If
we declareStack<String> s = new ... // depending how a stack is implementedthen
s.push("hello");
is legitimate but s.push(new Integer(0));will be rejected at compile-time. Furthermore s.pop() is now known by the compiler to be a String so that no type cast is necessary.
Notice that the use of the symbol E for the type parameter is conventional. Most other expressions you might think of using in its place could be substituted. For example, in the latest edition of the book by Weiss, type parameters are often indicated by AnyType, so that the generic Stack interface would be written as
public interface Stack<AnyType> {
public void push(AnyType item);
public AnyType pop();
...
}
In these notes I have used the more standard single letter for a type
parameter as, for example, in the generic version of the current
DataStructures package.