Construction. Type parameters

[comp1110-48]

A type parameter allows a class or interface to be written once and used with many different types, while retaining type safety (unlike Object). We write the type parameter in angle brackets after the class or interface name, and use it as a placeholder for a concrete type throughout. Referring to our GuestList example:

public interface GuestList<T> { void add(T name); void remove(T name); boolean isComing(T name); // note the additional argument here T[] coming(Function<Integer, T[]> arrayCreator); }

When using the interface, the caller fills in the placeholder with a concrete type:

GuestList<String> list = new ArrayGuestList<String>();

The compiler then treats every occurrence of T as String for that particular instance of the class. This means list.add(42) is a compile-time error, since 42 is not a String. Whereas using Object, such mistakes are only caught at run time.

This feature is also known as generics in Java, or more generally as parametric polymorphism.

bars magnifying-glass caret-down plus minus arrow-right xmark