Generic Class
A generic class is a class that can operate on a specific type specified by the programmer at compile time. To accomplish that, the class definition uses type parameters that act as variables that represent types (such as int
or String
).
To create a generic class, you list the type parameter after the class name in angle brackets. The type parameter specifies a name that you can use throughout the class anywhere you’d otherwise use a type. For example, here’s a simplified version of the class
declaration for the ArrayList
class:
public class ArrayList<E>
I left out the extends
and implements
clauses to focus on the formal type parameter: <E>
. The E
parameter specifies the type of the elements that are stored in the list.
To create an instance of a generic class, you must provide the actual type that will be used in place of the type parameter, like this:
ArrayList<String> myArrayList;
Here the E
parameter is String
, so the element type for this instance of the ArrayList
class is String
.
Now look at the declaration for the add
method for the ArrayList
class:
public boolean add(E o)
{
// body of method omitted (thank you)
}
Where you normally expect to see a parameter type, you see the letter E
. Thus, this method declaration specifies that the type for the o
parameter is the type specified for the formal type parameter E
. If E
is String
, the add
method accepts only String
objects. If you call the add
method passing anything other than a String
parameter, the compiler will generate an error message.
You can also use a type parameter as a return type. Here’s the declaration for the ArrayList
class get
method:
public E get(int index)
{
// body of method omitted (you’re welcome)
}
Here, E
is specified as the return type. That means that if E
is String
, this method returns String
objects.