Generics are a facility of
generic programming that were added to the
Java programming language
Java is a high-level, general-purpose, memory-safe, object-oriented programming language. It is intended to let programmers ''write once, run anywhere'' ( WORA), meaning that compiled Java code can run on all platforms that support Jav ...
in 2004 within version
J2SE 5.0. They were designed to extend Java's
type system
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
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'' required that parametrically polymorphic
functions are not implemented in the
Java virtual machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally descr ...
, since type safety is impossible in this case.
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 classification
According to ''Java Language Specification'':
*A
type variable
In type theory and programming languages, a type variable is a mathematical variable ranging over types. Even in programming languages that allow mutable variables, a type variable remains an abstraction, in the sense that it does not correspond ...
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. 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. 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.
Motivation
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an of type . Then, it adds a
String
to the
ArrayList
. Finally, it attempts to retrieve the added
String
and cast it to an
Integer
—an error in logic, as it impossible to cast any string instance to an integer.
final List v = new ArrayList();
v.add("test"); // A String that cannot be cast to an Integer
final Integer i = (Integer) v.get(0); // Run time error
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
logic error
In computer programming, a logic error is a Software bug, bug in a program that causes it to operate incorrectly, but not to terminate abnormally (or crash (computing), crash). A logic error produces unintended or undesired output or other behav ...
can be detected during compile time by using generics and is the primary motivation for using them. It defines one or more type variables that act as parameters.
The above code fragment can be rewritten using generics as follows:
final List v = new ArrayList();
v.add("test");
final Integer i = (Integer) v.get(0); // (type error) compilation-time error
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.
The logical flaw in the third line of this fragment will be detected as a
compile-time error (with J2SE 5.0 or later) because the compiler will detect that
v.get(0)
returns
String
instead of
Integer
. For a more elaborate example, see reference.
Here is a small excerpt from the definition of the interfaces and in package :
interface List
interface Iterator
Generic class definitions
Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in a
map:
public class Entry
This generic class could be used in the following ways, for example:
final Entry grade = new Entry("Mike", "A");
final Entry mark = new Entry("Mike", 100);
System.out.println("grade: " + grade);
System.out.println("mark: " + mark);
final Entry prime = new Entry(13, true);
if (prime.getValue())
else
It outputs:
grade: (Mike, A)
mark: (Mike, 100)
13 is prime.
Generic method definitions
Here is an example of a generic method using the generic class above:
public static Entry twice(Type value)
Note: If we remove the first
in the above method, we will get
compilation error (cannot find symbol "Type"), 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:
final Entry pair = Entry.twice("Hello");
The parameters can be explicitly added if needed:
final Entry pair = Entry.twice("Hello");
The use of
primitive types is not allowed, and
boxed versions must be used instead:
final Entry pair; // Fails compilation. Use Integer instead.
There is also the possibility to create generic methods based on given parameters.
public Type[] toArray(Type... elements)
In such cases you can't use primitive types either, e.g.:
Integer[] array = toArray(1, 2, 3, 4, 5, 6);
Diamond operator
Thanks to
type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
, Java SE 7 and above allow the programmer to substitute an empty pair of angle brackets (
<>
, called the ''diamond operator'') 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
Entry
can be rewritten as:
final Entry grade = new Entry<>("Mike", "A");
final Entry mark = new Entry<>("Mike", 100);
System.out.println("grade: " + grade);
System.out.println("mark: " + mark);
final Entry prime = new Entry<>(13, true);
if (prime.getValue()) System.out.println(prime.getKey() + " is prime.");
else System.out.println(prime.getKey() + " is not prime.");
Type wildcards
A 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
Collection
is parameterized by a wildcard:
final Collection> c = new ArrayList();
c.add(new Object()); // compile-time error
c.add(null); // allowed
Since we don't know what the element type of
c
stands for, we cannot add objects to it. The
add()
method takes arguments of type
E
, the element type of the
Collection
generic interface. When the actual type argument is
?
, it stands for some unknown type. Any method argument value we pass to the
add()
method 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
Null may refer to:
Science, technology, and mathematics Astronomy
*Nuller, an optical tool using interferometry to block certain sources of light Computing
*Null (SQL) (or NULL), a special marker and keyword in SQL indicating that a data value do ...
; which is a member of every type.
To specify the
upper bound
In mathematics, particularly in order theory, an upper bound or majorant of a subset of some preordered set is an element of that is every element of .
Dually, a lower bound or minorant of is defined to be an element of that is less ...
of a type wildcard, the keyword is used to indicate that the type argument is a subtype of the bounding class. So means that the given list contains objects of some unknown type which extends the
Number
class. For example, the list could be
List<Float>
or
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
List
nor
List
is a subtype of the other; even though
Integer
is a subtype of
Number
. So, any method that takes
List
as a parameter does not accept an argument of
List
. If it did, it would be possible to insert a
Number
that is not an
Integer
into it; which violates type safety. Here is an example that demonstrates how type safety would be violated if
List
were a subtype of
List
:
final List ints = new ArrayList<>();
ints.add(2);
final List nums = ints; // valid if List were a subtype of List according to substitution rule.
nums.add(3.14);
final Integer x = ints.get(1); // now 3.14 is assigned to an Integer variable!
The solution with wildcards works because it disallows operations that would violate type safety:
final List extends Number> nums = ints; // OK
nums.add(3.14); // compile-time error
nums.add(null); // allowed
To specify the lower bounding class of a type wildcard, the
super
keyword is used. This keyword indicates that the type argument is a supertype of the bounding class. So, could represent
List<Number>
or
List<Object>
. Reading from a list defined as returns elements of type
Object
. Adding to such a list requires either elements of type
Number
, any subtype of
Number
or
null
Null may refer to:
Science, technology, and mathematics Astronomy
*Nuller, an optical tool using interferometry to block certain sources of light Computing
*Null (SQL) (or NULL), a special marker and keyword in SQL indicating that a data value do ...
(which is a member of every type).
The mnemonic PECS (Producer Extends, Consumer Super) from the book Effective Java by
Joshua Bloch gives an easy way to remember when to use wildcards (corresponding to
covariance
In probability theory and statistics, covariance is a measure of the joint variability of two random variables.
The sign of the covariance, therefore, shows the tendency in the linear relationship between the variables. If greater values of one ...
and
contravariance) in Java.
Generics in throws clause
Although exceptions themselves cannot be generic, generic parameters can appear in a throws clause:
public void throwMeConditional(boolean conditional, T exception) throws T
Problems with type erasure
Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called
type erasure
In programming languages, type erasure is the load-time process by which explicit type annotations are removed from a program, before it is executed at run-time. Operational semantics not requiring programs to be accompanied by types are named ...
. 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 uses the correct type.
Because of type erasure, type parameters cannot be determined at run-time. For example, when an
ArrayList
is examined at runtime, there is no general way to determine whether, before type erasure, it was an
ArrayList<Integer>
or 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
ArrayList
contains an
Integer
, that ArrayList may have been parameterized with
Integer
(however, it may have been parameterized with any parent of
Integer
, such as
Number
or
Object
).
Demonstrating this point, the following code outputs "Equal":
final List li = new ArrayList<>();
final List lf = new ArrayList<>();
if (li.getClass() lf.getClass())
Another effect of type erasure is that a generic class cannot extend the
Throwable
class in any way, directly or indirectly:
public class GenericException extends Exception
The reason why this is not supported is due to type erasure:
try
catch (GenericException e)
catch (GenericException e)
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:
T instantiateElementType(List arg)
Because there is only one copy per generic class at runtime,
static variable
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s 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.
Type erasure was implemented in Java to maintain
backward compatibility
In telecommunications and computing, backward compatibility (or backwards compatibility) is a property of an operating system, software, real-world product, or technology that allows for interoperability with an older legacy system, or with Input ...
with programs written prior to Java SE5.
Differences from Arrays
There are several important differences between arrays (both primitive arrays and arrays), and generics in Java. Two of the major differences, namely, differences in terms of
variance
In probability theory and statistics, variance is the expected value of the squared deviation from the mean of a random variable. The standard deviation (SD) is obtained as the square root of the variance. Variance is a measure of dispersion ...
and
reification.
Covariance, contravariance and invariance
Generics are invariant, whereas arrays are
covariant. This is a benefit of using generic when compared to non-generic objects such as arrays. Specifically, generics can help prevent run time exceptions by throwing a compile-time exception to force the developer to fix the code.
For example, if a developer declares an object and instantiates the object as a new object, no compile-time exception is thrown (since arrays are covariant). This may give the false impression that the code is correctly written. However, if the developer attempts to add a to this object, the program will throw an . This run-time exception can be completely avoided if the developer uses generics.
If the developer declares a object an creates a new instance of this object with return type , the Java compiler will (correctly) throw a compile-time exception to indicate the presence of incompatible types (since generics are invariant). Hence, this avoids potential run-time exceptions. This problem can be fixed by creating an instance of using object instead. For code using Java SE7 or later versions, the can be instantiated with an object using the
diamond operator
Reification
Arrays are
reified, meaning that an array object enforces its type information at run-time, whereas generics in Java are not reified.
More formally speaking, objects with generic type in Java are non-reifiable types. A non-reifiable type is type whose representation at run-time has less information than its representation at compile-time.
Objects with generic type in Java are non-reifiable due to type erasure. Java only enforces type information at compile-time. After the type information is verified at compile-time, the type information is discarded, and at run-time, the type information will not be available.
Examples of non-reifiable types include and , where is a generic formal parameter.
Project on generics
Project Valhalla is an experimental project to incubate improved Java generics and language features, for future versions potentially from Java 10 onwards. Potential enhancements include:
*
generic specialization, e.g. List
* reified generics; making actual types available at runtime.
See also
* Generic programming
* Template metaprogramming
* Wildcard (Java)
* Comparison of C# and Java
* Comparison of Java and C++
Citations
References
*
{{DEFAULTSORT:Generics In Java
Java (programming language)
Polymorphism (computer science)