Generics 101, Part 2: Exploring Generics Through a Generic Stack Type
Editor's Note: This is Part 2 of a 3 part series. Be sure to start by reading Part 1 first.
Generics are language features that many developers have difficulty grasping. Removing this difficulty is the focus of this three-part series on generics.
Part 1 introduced generics by explaining what they are with an emphasis on generic types and parameterized types. It also explained the rationale for bringing generics to Java.
This article digs deeper into generics by focusing on a generic Stack type. After showing you how to codify this type, the article explores unbounded and bounded type parameters, type parameter scope, and wildcard arguments in the context of Stack.
Exploring Generics Through a Generic Stack Type
Declaring your own generic types need not be a difficult task. Start by declaring a formal type parameter list after the class or interface name, and then, throughout the generic type's body, replace those types that will correspond to the actual type arguments passed to the generic type when it's instantiated with type parameters from its formal type parameter list. For example, consider Listing 1's Stack<E> generic type.
Listing 1Stack.java
// Stack.java public class Stack<E> { private E[] elements; private int top; @SuppressWarnings("unchecked") public Stack(int size) { elements = (E[]) new Object[size]; top = -1; } public void push(E element) throws StackFullException { if (top == elements.length-1) throw new StackFullException(); elements[++top] = element; } E pop() throws StackEmptyException { if (isEmpty()) throw new StackEmptyException(); return elements[top--]; } public boolean isEmpty() { return top == -1; } public static void main(String[] args) throws StackFullException, StackEmptyException { Stack<String> stack = new Stack<String>(5); stack.push("First"); stack.push("Second"); stack.push("Third"); stack.push("Fourth"); stack.push("Fifth"); // Uncomment the following line to generate a StackFullException. //stack.push("Sixth"); while (!stack.isEmpty()) System.out.println(stack.pop()); // Uncomment the following line to generate a StackEmptyException. //stack.pop(); } } class StackEmptyException extends Exception { } class StackFullException extends Exception { }
Stack<E> describes a stack data structure that stores elements (of placeholder type E) in a last-in, first-out order. Elements are pushed onto the stack via the void push(E element) method and popped off the stack via the E pop() method. The element at the top of the stack is the next element to be popped.
Stack instances store their elements in the array identified as elements. This array's element type is specified by type parameter E, which will be replaced by the actual type argument that's passed to Stack<E> when this generic type is instantiated. For example, Stack<String> instantiates this type to store Strings in the array.
The constructor instantiates an array and assigns its reference to elements. Perhaps you're wondering why I've assigned (E[]) new Object[size] instead of the more logical new E[size] to elements. I've done so because it's not possible to assign the latter more compact representation; I'll explain why in Part 3.
The E[] cast causes the compiler to generate a warning message about the cast being unchecked, because the downcast from Object[] to E[] could result in a type safety violation[md]any kind of object can be stored in Object[]. Because there's no way for a non-E object to be stored in elements, however, I've suppressed this warning by prefixing the constructor with @SuppressWarnings("unchecked").
Listing 1 generates the following output:
Fifth Fourth Third Second First
Unbounded and Upper-Bounded Type Parameters
Stack<E>'s E type parameter is an example of an unbounded type parameter because any kind of actual type argument can be passed to E. In some situations, you'll want to restrict the kinds of actual type arguments that can be passed. For example, suppose you only want to push objects whose types subclass the abstract Number class onto the stack.
You can limit actual type arguments by assigning an upper bound, which is a type that serves as an upper limit on types that can be chosen as actual type arguments, to a type parameter. Specify an upper bound by suffixing the type parameter with keyword extends followed by a type name. For example, Stack<E extends Number> limits type arguments to Number and its subclasses (such as Integer and Double).
After making this change, specifying Stack<Number> stack = new Stack<Number>(5); lets an application store a maximum of five Number subclass objects on the stack. For example, stack.push(1); and stack.push(2.5); store an Integer object followed by a Double object. (Autoboxing expands these expressions to stack.push(new Integer(1)); and stack.push(new Double(2.5));.)
Perhaps you would like to assign more than one upper bound to a type parameter, so that only actual type arguments that satisfy each bound can be passed to the generic type. You can do this provided that the first upper bound is a class, the remaining upper bounds are interfaces, and each upper bound is separated from its predecessor via the ampersand (&) character.
For example, suppose you only want to push objects onto the stack whose types subclass Number and implement Comparable<T>. In other words, you only want to push Number subclass objects that can be compared to each other. You can accomplish this task by specifying Stack<E extends Number implements Comparable<E>>.
Given this generic type, you can specify Stack<Integer> and Stack<Double> because Integer and Double subclass Number and implement Comparable<T>. However, you cannot specify Stack<Number> and Stack<AtomicInteger> because neither Number nor java.util.concurrent.atomic.AtomicInteger implements Comparable<T>.
Type Parameter Scope
Type parameters are scoped (have visibility) like any other variable. The scope begins with a class's or interface's formal type parameter list and continues with the rest of the class/interface except where masked (hidden). For example, E's scope in Stack<E extends Number implements Comparable<E>> begins with E extends Number implements Comparable<E> and continues with the rest of this class.
It's possible to mask a type parameter by declaring a same-named type parameter in the formal type parameter section of a nested type. For example, considered the following nested class scenario:
class Outer<T> { class Inner<T extends Number> { } }
Outer's T type parameter is masked by Inner's T type parameter, which is upper-bounded by Number. Referencing T from within Inner refers to the bounded T and not the unbounded T passed to Outer.
If masking proves to be undesirable, you should choose a different name for one of the type parameters. For example, given the previous code fragment, you might choose U as the name of Inner's type parameter. This is one situation where choosing a meaningless type parameter name is justified.
Wildcard Arguments
Suppose you decide to modify Listing 1 by introducing an outputStack() method that encapsulates the while loop that pops objects from a stack and outputs them. After thinking about this task, you create the following method:
static void outputStack(Stack<Object> stack) throws StackEmptyException { while (!stack.isEmpty()) System.out.println(stack.pop()); }
This method takes a single argument of Stack<Object> type. You specified Object because you want to be able to call outputStack() with any Stack object regardless of its element type (Stack of String or Stack of Integer, for example).
Thinking that you've accomplished your task, you add this method to Listing 1's Stack class and place an outputStack(stack); method call in main(). Next, you compile the source code, and are surprised when the compiler outputs the following (reformatted) error message:
Stack.java:43: outputStack(Stack<java.lang.Object>) in Stack<E> cannot be applied to (Stack<java.lang.String>) outputStack(stack); ^ 1 error
This error message results from being unaware of the fundamental rule of generic types:
for a given subtype x of type y, and given G as a raw type declaration, G<x> is not a subtype of G<y>.
To understand this rule, think about polymorphism (many shapes). For example, Integer is a kind of Number. Similarly, Set<Country> is a kind of Collection<Country> because polymorphic behavior also applies to related parameterized types with identical type parameters.
In contrast, polymorphic behavior doesn't apply to multiple parameterized types that differ only where one type parameter is a subtype of another type parameter. For example, List<Integer> is not a subtype of List<Number>.
The reason for this restriction can best be explained by an example. Consider the following code fragment:
List<Integer> li = new ArrayList<Integer>(); List<Number> ln = li; // upcast List of Integer to List of Number (illegal) ln.add(new Double(2.5)); // or ln.add(2.5); thanks to autoboxing Integer i = li.get(0);
This code fragment will not compile because it violates type safety. If it did compile, ClassCastException would be thrown at runtime because of the implicit cast to Integer in the final line. After all, a Double has been stored but an Integer is expected.
Consider error message
outputStack(Stack<java.lang.Object>) in Stack<E> cannot be applied to (Stack<java.lang.String>)
This message reveals that Stack of String isn't also Stack of Object.
To call outputStack() without violating type safety, you can only pass an argument of Stack<Object> type, which limits this method's usefulness. After all, you want the freedom to pass Stack objects of any element type.
Fortunately, generics offer a solution: the wildcard argument (?), which stands for any type. By changing outputStack()'s parameter type from Stack<Object> to Stack<?>, you can call outputStack() with a Stack of String, a Stack of Integer, and so on.
The reason why the compiler allows the wildcard in this example is that type safety isn't being violated. The outputStack() method is only outputting the Stack argument's contents; it isn't changing these contents.