Generics in Java
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.
Hierarchy and classificationAccording to Java Language Specification:
- A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.
- A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.
- An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.
- A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.
- A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface.
Object. Then, it adds a
ArrayList. Finally, it attempts to retrieve the added
Stringand cast it to an
Integer—an error in logic, as it is not generally possible to cast an arbitrary string to an integer.
List v = new ArrayList;
v.add; // A String that cannot be cast to an Integer
Integer i = v.get; // Run time error
Although the code is compiled without error, it throws a runtime exception when executing the third line of code. This type of logic error can be detected during compile time by using generics and is the primary motivation for using them.
The above code fragment can be rewritten using generics as follows:
Integer i = v.get; // compilation-time error
The type parameter
Stringwithin the angle brackets declares the
ArrayListto be constituted of
String. With generics, it is no longer necessary to cast the third line to any particular type, because the result of
v.getis defined as
Stringby the code generated by the compiler.
The logical flaw in the third line of this fragment will be detected as a compile-time error because the compiler will detect that
Integer. For a more elaborate example, see reference.
Here is a small excerpt from the definition of the interfaces
Iteratorin package :
public interface List
public interface Iterator
Type wildcardsA type argument for a parameterized type is not limited to a concrete class or interface. Java allows the use of type wildcards to serve as type arguments for parameterized types. Wildcards are type arguments in the form "
>"; optionally with an upper or lower bound. Given that the exact type represented by a wildcard is unknown, restrictions are placed on the type of methods that may be called on an object that uses parameterized types.
Here is an example where the element type of a
Collectionis parameterized by a wildcard:
Collection> c = new ArrayList
c.add); // compile-time error
c.add; // allowed
Since we don’t know what the element type of
cstands for, we cannot add objects to it. The
addmethod takes arguments of type
E, the element type of the
Collectiongeneric interface. When the actual type argument is
?, it stands for some unknown type. Any method argument value we pass to the
addmethod would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null; which is a member of every type.
To specify the upper bound of a type wildcard, the
extendskeyword is used to indicate that the type argument is a subtype of the bounding class. So
List<? extends Number>means that the given list contains objects of some unknown type which extends the
Numberclass. For example, the list could be
List<Number>. Reading an element from the list will return a
Number. Adding null elements is, again, also allowed.
The use of wildcards above adds flexibility since there is not any inheritance relationship between any two parameterized types with concrete type as type argument. Neither
Listis a subtype of the other; even though
Integeris a subtype of
Number. So, any method that takes
Listas a parameter does not accept an argument of
List. If it did, it would be possible to insert a
Numberthat is not an
Integerinto it; which violates type safety. Here is an example that demonstrates how type safety would be violated if
Listwere a subtype of
Integer x = ints.get; // now 3.14 is assigned to an Integer variable!
The solution with wildcards works because it disallows operations that would violate type safety:
List extends Number> nums = ints; // OK
nums.add; // compile-time error
nums.add; // allowed
To specify the lower bounding class of a type wildcard, the
superkeyword is used. This keyword indicates that the type argument is a supertype of the bounding class. So,
List<? super Number>could represent
List<Object>. Reading from a list defined as
List<? super Number>returns elements of type
Object. Adding to such a list requires either elements of type
Number, any subtype of
The mnemonic PECS from the book Effective Java by Joshua Bloch gives an easy way to remember when to use wildcards in Java.
Generic class definitionsHere is an example of a generic Java class, which can be used to represent individual entries in a map:
public class Entry
This generic class could be used in the following ways, for example:
if ) System.out.println;
13 is prime.
Diamond operatorThanks to type inference, Java SE 7 and above allow the programmer to substitute an empty pair of angle brackets for a pair of angle brackets containing the one or more type parameters that a sufficiently-close context implies. Thus, the above code example using
Entrycan be rewritten as:
if ) System.out.println;
Generic method definitionsHere is an example of a generic method using the generic class above:
Note: If we remove the first
in the above method, we will get compilation error since it represents the declaration of the symbol.
In many cases the user of the method need not indicate the type parameters, as they can be inferred:
The parameters can be explicitly added if needed:
The use of primitive types is not allowed, and boxed versions must be used instead:
There is also the possibility to create generic methods based on given parameters.
In such cases you can't use primitive types either, e.g.:
Integer array = toArray;
Generics in throws clauseAlthough exceptions themselves cannot be generic, generic parameters can appear in a throws clause:
Problems with type erasureGenerics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example,
List<Integer>will be converted to the non-generic type
List, which ordinarily contains arbitrary objects. The compile-time check guarantees that the resulting code is type-correct.
Because of type erasure, type parameters cannot be determined at run-time. For example, when an
ArrayListis examined at runtime, there is no general way to determine whether, before type erasure, it was an
ArrayList<Float>. Many people are dissatisfied with this restriction. There are partial approaches. For example, individual elements may be examined to determine the type they belong to; for example, if an
Integer, that ArrayList may have been parameterized with
Demonstrating this point, the following code outputs "Equal":
Another effect of type erasure is that a generic class cannot extend the Throwable class in any way, directly or indirectly:
public class GenericException
The reason why this is not supported is due to type erasure:
Due to type erasure, the runtime will not know which catch block to execute, so this is prohibited by the compiler.
Java generics differ from C++ templates. Java generics generate only one compiled version of a generic class or function regardless of the number of parameterizing types used. Furthermore, the Java run-time environment does not need to know which parameterized type is used because the type information is validated at compile-time and is not included in the compiled code. Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown.
For example, the following code cannot be compiled:
Because there is only one copy per generic class at runtime, static variables are shared among all the instances of the class, regardless of their type parameter. Consequently, the type parameter cannot be used in the declaration of static variables or in static methods.