We can use a generic type parameter to allow generalising a class for any input type. This is useful for lists or containers of some sort:
public class Pair<E1, E2> {
private E1 fst;
private E2 snd;
public Pair(E1 e1, E2 e2) { fst = e1; snd = e2; };
}We can then declare methods that use these type parameters, such as .add(E1 fst);
Erasure
Because previous Java versions had no concept of generics, the functionality was implemented using type erasure.
At compile time, all type parameters are replaced by Object after typechecking.
This has consequences:
- We cannot use overloading for different type parameters:
public add(List<String> l);is the same method asadd(List<Integer> l);during compile time, which results in a compiler error. - We cannot instantiate a
new E();→ Compile Error - Same for
E[]Which can be solved by doing(E[]) new Object[]; - If two arraylists are empty, but of different types:
List<Integer>andList<Double>they will be equal for a.equals()call (as long as empty).