| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/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:
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(); }
Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in a map:
This generic class could be used in the following ways, for example:
It outputs:
Entry<String,String>pair=Entry.twice("Hello");The parameters can be explicitly added if needed:
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.
In such cases one cannot use primitive types either, e.g.:
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.
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:
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:
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:
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.
Type erasure was implemented in Java to maintain backward compatibility with programs written prior to Java SE5.
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.
| View original on Wikipedia | Back | FazBrowse Home |