How to Write Type Parameters with Multiple Bounds in Java
A generic type can be bounded with multiple class data types. The class types that qualify are subclasses of a specified data type or implementations of an interface. For example, we might wish to create a vector or array list and call a method in a generic class to process the data. Both the ArrayList
and Vector
classes are implementations of the List
interface. Therefore the bounds of the generic parameter are the implementations of List
. To learn how to write type parameters with multiple bounds in Java, follow these four steps.
- Open your text editor and type in the following Java statements:
The classGenericsMultipleBounds
(line 15) is defined with the clause<T extends List>
which means the generic type is bounded by implementations of theList
interface.ArrayList
andVector
are common examples ofList
implementations and are referred to as collections. The main method instantiates twoGenericMultipleBounds
objects. An array list is passed to the first object'sdisplay
method. A vector is passed to the second object'sdisplay
method. Thedisplay
method will print the first item of the collection that was passed. - Save your file as WriteTypeParametersWithMultipleBounds.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Type in the command to run your program and hit Enter. Notice in the output that the first item of the array list was displayed followed by the first item stored in the vector.