Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety”. The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.
The Java collections framework supports generics to specify the type of objects stored in a collection instance.
In 1998, Gilad Bracha, Martin Odersky, David Stoutamire and Philip Wadler created Generic Java, an extension to the Java language to support generic types. Generic Java was incorporated in Java with the addition of wildcards.
According to Java Language Specification:
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList
of type Object
. Then, it adds a String
to the ArrayList
. Finally, it attempts to retrieve the added String
and cast it to an Integer
.
Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException
) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
Using generics, the above code fragment can be rewritten as follows:
The type parameter String
within the angle brackets declares the ArrayList
to be constituted of String
(a descendant of the ArrayList
's generic Object
constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0)
is defined as String
by the code generated by the compiler.
Compiling the third line of this fragment with J2SE 5.0 (or later) will yield a compile-time error because the compiler will detect that v.get(0)
returns String
instead of Integer
. For a more elaborate example, see reference.