Enter Generics
Generics are an enhancement to the syntax of classes that allow us to specialize the class for a given type or set of types. A generic class requires one or more type parameters wherever we refer to the class type and uses them to customize itself.
If you look at the source or Javadoc for the List class, for example, you’ll see it defined
something like this:
publicclassList<E>{...publicvoidadd(Eelement){...}publicEget(inti){...}}
The identifier E between the angle
brackets (<>) is a type
variable. It indicates that the class List is generic and requires a Java type as an
argument to make it complete. The name E is arbitrary, but there are conventions that
we’ll see as we go on. In this case, the type variable E represents the type of elements we want to
store in the list. The List class
refers to the type variable within its body and methods as if it were a
real type, to be substituted later. The type variable may be used to
declare instance variables, arguments to methods, and the return type of
methods. In this case, E is used as the
type for the elements we’ll be adding via the add() method and the return type of the get() method. Let’s see how to use it.
The same angle bracket syntax supplies the type parameter when we
want to use the List type:
List<String>listOfStrings;
In this snippet, we declared a variable called listOfStrings using the generic type List with a type parameter of String. String refers to the String class, but we could ...