next up previous index
Next: New approach Up: Generics in Java 5 Previous: Generics in Java 5   Index


Generic types

Generic programming in earlier versions of Java needed to use Object as the basic element of a data structure. For example, a generic stack might have the interface

public interface Stack {
    public void push(Object item);
    public Object pop();
    ...
}
This has the following drawbacks.
  1. It allows any Object whatever to be pushed onto the stack. But the stack may only be intended to hold strings, for example, i.e. to have homogeneous elements of a more specific type than Object. In that case it would useful to have the restriction enforced at compile-time.
  2. Anything popped from the stack will usually need a type cast before anything useful can be done with it. For example, the code
    Stack s = new ... // depending how the stack is implemented
    s.push("hello");
    int len = s.pop().length();
    
    will not compile, because raw objects don't have lengths. It will be necessary to write
       int len = ((String) s.pop()).length();
    
    and it is worth noting that, in general, such a type cast only expresses an expectation on the part of the programmer, which may prove false at run-time.



Subsections

Peter Williams 2005-06-07