FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Generics_in_Java#Diamond_operator

Generics in Java

Contents
Generic class definitions
Type wildcards
Differences from Arrays
    Covariance, contravariance and invariance
    Reification
See also
Citations

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 required that parametrically polymorphic functions are not implemented in the Java virtual machine, 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.

java.util.ArrayList of type 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:

v = new ArrayList<String>();\nv.add(\"test\");\nInteger i = (Integer)v.get(0); // (type error) compilation-time error\n"}}'>importjava.util.ArrayList; importjava.util.List; List<String>v=newArrayList<String>(); v.add("test"); Integeri=(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 java.util.List and interface List<E>{ voidadd(Ex); Iterator<E>iterator(); } interface Iterator<E>{ Enext(); booleanhasNext(); }

Generic class definitions

edit

Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in a map:

{\n private K key;\n private V value;\n\n public Entry(K key, V value) { \n this.key = key;\n this.value = value;\n }\n\n public K getKey() {\n return key;\n }\n\n public V getValue() {\n return value;\n }\n\n public String toString() { \n return String.format(\"(%s, %s)\", key, value);\n }\n}\n"}}'>publicclass Entry<K,V>{ privateKkey; privateVvalue; publicEntry(Kkey,Vvalue){ this.key=key; this.value=value; } publicKgetKey(){ returnkey; } publicVgetValue(){ returnvalue; } publicStringtoString(){ returnString.format("(%s, %s)",key,value); } }

This generic class could be used in the following ways, for example:

grade = new Entry<String, String>(\"Mike\", \"A\");\nEntry<String, Integer> mark = new Entry<String, Integer>(\"Mike\", 100);\nSystem.out.printf(\"grade: %s%n\", grade);\nSystem.out.printf(\"mark: %s%n\", mark);\n\nEntry<Integer, Boolean> prime = new Entry<>(13, true);\nif (prime.getValue()) {\n System.out.println(\"%s is prime.%n\", prime.getKey());\n} else {\n System.out.println(\"%s is not prime.%n\", prime.getKey());\n}\n"}}'>Entry<String,String>grade=newEntry<String,String>("Mike","A"); Entry<String,Integer>mark=newEntry<String,Integer>("Mike",100); System.out.printf("grade: %s%n",grade); System.out.printf("mark: %s%n",mark); Entry<Integer,Boolean>prime=newEntry<>(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:

Entry<String,String>pair=Entry.twice("Hello");

The parameters can be explicitly added if needed:

pair = Entry.<String>twice(\"Hello\");\n"}}'>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, pair;"}}'>Entry<int,int>pair; fails compiling, and should instead be using the wrapper classes for primitives (like pair;"}}'>Entry<Integer,Integer>pair;.

There is also the possibility to create generic methods based on given parameters.

T[] toArray(T... elements) {\n return elements;\n}\n"}}'>public<T>T[]toArray(T...elements){ returnelements; }

In such cases one cannot use primitive types either, e.g.:

Entry<String,String>grade=newEntry<>("Mike","A"); Entry<String,Integer>mark=newEntry<>("Mike",100); System.out.printf("grade: %s%n",grade); System.out.printf("mark: %s%n",mark); Entry<Integer,Boolean>prime=newEntry<>(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.

\nclass Box {\n // ...\n};\n\nBox<> v; // refers to Box<int>\n"}}'>template<typenameT=int> classBox{ // ... }; Box<>v;// refers to Box<int>

Type wildcards

edit

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:

c = new ArrayList<String>();\nc.add(new Object()); // compile-time error\nc.add(null); // allowed\n"}}'>importjava.util.ArrayList; importjava.util.Collection; Collection<?>c=newArrayList<String>(); c.add(newObject());// compile-time error c.add(null);// allowed

Since the element type of c is not known, objects cannot be added to it. The add() method takes arguments of type E, the element type of the java.util.Collection<E> generic interface. When the actual type argument is ?, it stands for some unknown type. Any method argument value passed 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 importjava.util.ArrayList; importjava.util.List; List<Integer>intList=newArrayList<>(); 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); Integerx=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:

nums = ints; // OK\nnums.add(3.14); // compile-time error\nnums.add(null); // allowed \n"}}'>importjava.util.List; List<?extendsNumber>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 List<?superNumber> returns elements of type java.lang.Object. Adding to such a list requires either elements of type java.lang.Number, any subtype of java.lang.Number or throws clause.

The following pattern, sometimes known as the generic rethrow or sneaky throw, is used to bypass checked exceptions entirely, such as in the Project Lombok importjava.util.ArrayList; importjava.util.List; List<Integer>li=newArrayList<>(); List<Float>lf=newArrayList<>(); if(li.getClass()==lf.getClass()){// evaluates to true System.out.println("Equal"); }

Another effect of type erasure is that a generic class cannot extend the java.lang.Throwable class in any way, directly or indirectly:

extends Exception {\n // ...\n}\n"}}'>// causes a compile error publicclass GenericException<T>extendsException{ // ... }

The reason why this is not supported is due to type erasure:

();\n} catch (GenericException<Integer> e) {\n System.err.println(\"Integer\");\n} catch (GenericException<String> e) {\n System.err.println(\"String\");\n}\n"}}'>try{ thrownewGenericException<Integer>(); }catch(GenericException<Integer>e){ System.err.println("Integer"); }catch(GenericException<String>e){ System.err.println("String"); }

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<T> arg) {\n return new T(); // causes a compile error\n}\n"}}'>importjava.util.List; <T>TinstantiateElementType(List<T>arg){ returnnewT();// causes a compile error }

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.

Type erasure was implemented in Java to maintain backward compatibility with programs written prior to Java SE5.

Differences from Arrays

edit

There are several important differences between arrays (both primitive arrays and java.lang.Object arrays), and generics in Java. Two of the major differences, namely, differences in terms of variance and reification.

Covariance, contravariance and invariance

edit
Collection<Object> object and creates a new instance of this object with return type "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"ArrayList<Long>"}},"i":0}}]}'>ArrayList<Long>, 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 "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"Collection<Object>"}},"i":0}}]}'>Collection<Object> using "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"ArrayList<Object>"}},"i":0}}]}'>ArrayList<Object> object instead. For code using Java SE7 or later versions, the "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"Collection<Object>"}},"i":0}}]}'>Collection<Object> can be instantiated with an "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"ArrayList<>"}},"i":0}}]}'>ArrayList<> object using the diamond operator.

Reification

edit
List<T> and "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"List<String>"}},"i":0}}]}'>List<String>, where List<Integer>
  • reified generics; making actual types available at runtime.
  • See also

    edit

    Citations

    edit
    Oracle Corporation (6 June 2026). "Interface PrimitiveIterator<T,T_CONS>". docs.oracle.com. Oracle Corporation.
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Bloch 2018, pp. 126–129, Chapter §5 Item 28: Prefer lists to arrays.
  • Bloch 2018, pp. 117–122, Chapter §5 Item 26: Don't use raw types.
  • ↑ Bloch 2018, pp. 135–138, Chapter §5 Item 30: Favor generic methods.
  • ↑ Gilad Bracha (July 5, 2004). "Generics in the Java Programming Language" (PDF). www.oracle.com. p. 5.
  • 1 2 3 4 Bloch 2018, pp. 139–145, Chapter §5 Item 31: Use bounded wildcards to increase API flexibility.
  • ↑ Bonus > Generics"},"last":{"wt":"Bracha"},"first":{"wt":"Gilad"},"author-link":{"wt":"Gilad Bracha"},"publisher":{"wt":"Oracle"},"website":{"wt":"The Java™ Tutorials"},"quote":{"wt":"...The sole exception is null, which is a member of every type..."}},"i":0}}]}'/>Bracha, Gilad. "Wildcards > Bonus > Generics". The Java™ Tutorials. Oracle. ...The sole exception is null, which is a member of every type...
  • ↑ "Java Language Specification, Section 8.1.2". Oracle. Retrieved 24 October 2015.
  • ↑

  • View original on Wikipedia | Back | FazBrowse Home