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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access