Generics

Updated: 10 September 2022

Taken from O’Reilly ‘Learning Java 4th edition’.

Generics are an enhancement to class syntax which allows a class to be specialised for given types. A generic class requires one or more type parameters and uses these to customise itself.

Below, E is a type variable. It indicates the class is generic and requires a Java type as an argument to make it complete:

public class List<E> {
    public void add( E element ) { ... }
    public E get( int i ) { ... }
}

The List class refers to the type variable as if it were a real type, to be substituted later. The type variable may be used to declare:

  1. instance variables
  2. method arguments
  3. method return types

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 have specialised List with any Java class type. For example:

List<Date> dates;
List<java.math.BigDecimal> decimals;
List<Foo> foos;

Leave a comment