Generics

suggest change

Versions

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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents