Generics
suggest changeVersions
Java SE 5, Java SE 6, Java SE 7, Java SE 8, Java SE 9 (Early Access)
Introduction
Generics are a facility of generic programming that extends Java’s type system to allow a type or method to operate on objects of various types while providing compile-time type safety. In particular, the Java collections framework uses generics to specify the type of objects stored in a collection instance.
Syntax
- class ArrayList<E> {} // a generic class with type parameter E
- class HashMap<K, V> {} // a generic class with two type parameters K and V
- <E> void print(E element) {} // a generic method with type parameter E
- ArrayList<String> names; // variable whose type is a parameterization of a generic class
- ArrayList<?> objects; // variable with an unknown type argument
- new ArrayList<String>() // instantiation of a generic class
- new ArrayList<>() // instantiation with type inference “diamond” (Java 7 or later)
Remarks
Generics are implemented through type erasure: the type arguments of a generic instance are not stored in the object. For example, List<String> names = new ArrayList<>(); produces a list object from which the element type String cannot be recovered. If a field, method or constructor parameter, or method return type is declared as List<String>, that declaration's generic signature can be read back through reflection. The list object itself still does not carry the type argument.
A cast to a generic type (for example (List<String>) list) is an unchecked cast. Because <String> is erased, the JVM cannot check a cast from List<?> to List<String>. At runtime it only checks that the value is a List.