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".Java Programming Language The aspect compile-time type safety required that parametrically polymorphic functions are not implemented in the Java virtual machine, since type safety is impossible in this case.A ClassCastException can be thrown even in the absence of casts or nulls.
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.GJ: Generic Java Generic Java was incorporated in Java with the addition of wildcards.
Hierarchy and classification According to Java Language Specification:Java Language Specification, Third Edition by James Gosling, Bill Joy, Guy Steele, Gilad Bracha – Prentice Hall PTR 2005 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. These are often a single capital letter, but those longer than one letter are typically written in (unlike other languages like C++, C#, and Rust where they are ), for instance java.util.PrimitiveIterator<T, T_CONS>. 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 java.lang.String to the java.util.ArrayList. Finally, it attempts to retrieve the added java.lang.String and cast it to an java.lang.Integer—an error in logic, as it is impossible to cast any string instance to an integer.
import java.util.ArrayList; import java.util.List;
List v = new ArrayList(); v.add("test"); // A String that cannot be cast to an Integer Integer i = (Integer)v.get(0); // Run time error
This is similar to C, which lacks generics, and its collection-like data structures typically store data as void* (a void pointer), from which objects must be cast explicitly.
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 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:
import java.util.ArrayList; import java.util.List;
List<String> v = new ArrayList<String>(); v.add("test"); Integer i = (Integer)v.get(0); // (type error) compilation-time error
The type parameter java.lang.String within the angle brackets declares the java.util.ArrayList to be constituted of java.lang.String (a descendant of the java.util.ArrayList's generic java.lang.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 java.lang.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 java.lang.String instead of java.lang.Integer. For a more elaborate example, see reference.
Here is a small excerpt from the definition of the interfaces and in package :
interface List<E> { void add(E x); Iterator<E> iterator(); }
interface Iterator<E> { E next(); boolean hasNext(); }
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<K, V> { private K key; private V value;
public Entry(K key, V value) { this.key = key; this.value = value;
public K getKey() { return key;
public V getValue() { return value;
public String toString() { return String.format("(%s, %s)", key, value);
This generic class could be used in the following ways, for example:
Entry<String, String> grade = new Entry<String, String>("Mike", "A"); Entry<String, Integer> mark = new Entry<String, Integer>("Mike", 100); System.out.printf("grade: %s%n", grade); System.out.printf("mark: %s%n", mark);
Entry<Integer, Boolean> prime = new Entry<>(13, true); if (prime.getValue()) { System.out.println("%s is prime.%n", prime.getKey()); } else { System.out.println("%s is not prime.%n", prime.getKey()); }
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, for a generic type T: public static <T> Entry<T, T> twice(T value) { return new Entry<T, T>(value, value); }
In many cases, the user of the method need not indicate the type parameters, as they can be inferred:
Entry<String, String> pair = Entry.twice("Hello");
The parameters can be explicitly added if needed:
Entry<String, String> pair = Entry.<String>twice("Hello");
The use of primitive types is not allowed, and boxed versions must be used instead; only reference types may be stored in a generic type parameter. For instance, Entry<int, int> pair; fails compiling, and should instead be using the wrapper classes for primitives (like Entry<Integer, Integer> pair;.
There is also the possibility to create generic methods based on given parameters.
public <T> T[] toArray(T... elements) { return elements; }
In such cases one cannot use primitive types either, e.g.:
Integer[] array = toArray(1, 2, 3, 4, 5, 6);
While primitives cannot be stored, arrays of primitives (as they are objects, not primitives themselves) can: import java.util.ArrayList; import java.util.List;
// List<int[]> and List<Integer[]> are equally acceptable List<int[]> listOfArrays = new ArrayList<>(); List<Integer[]> myOtherList = listOfArrays;
Diamond operator Using type inference, 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. While <> is often called the "diamond operator", it is not an operator, just an empty type parameter list.
Thus, the above code example using Entry can be rewritten as:
Entry<String, String> grade = new Entry<>("Mike", "A"); Entry<String, Integer> mark = new Entry<>("Mike", 100);
System.out.printf("grade: %s%n", grade); System.out.printf("mark: %s%n", mark);
Entry<Integer, Boolean> prime = new Entry<>(13, true); if (prime.getValue()) { System.out.println("%s is prime.%n", prime.getKey()); } else { System.out.println("%s is not prime.%n", prime.getKey()); }
The so-called diamond operator does not exist in other Java-derived languages like C# or Kotlin, which have their own ways to avoid redundant type information. While something visually similar exists in C++, it does not denote type parameter deduction, but rather refers to only the default type parameter. template <typename T = int> class Box { // ...
Box<> v; // refers to Box<int>
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 java.util.Collection<E> is parameterized by a wildcard:
import java.util.ArrayList; import java.util.Collection;
Collection<?> c = new ArrayList<String>(); 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<E> 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; which is a member of every type.
To specify the upper bound 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<Number> nor List<Integer> is a subtype of the other; even though java.lang.Integer is a subtype of java.lang.Number. So, any method that takes List<Number> as a parameter does not accept an argument of List<Integer>. If it did, it would be possible to insert a java.lang.Number that is not an java.lang.Integer into it; which violates type safety. Here is an example that demonstrates how type safety would be violated if List<Integer> were a subtype of List<Number>:
import java.util.ArrayList; import java.util.List;
List<Integer> intList = new ArrayList<>(); intList.add(2); List<Number> nums = intList; // valid if List<Integer> were a subtype of List<Number> according to substitution rule. nums.add(3.14); Integer x = intList.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:
import java.util.List;
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 (which is a member of every type).