- Generics in Java
Generics are a facility of
generic programming that was added to the Java programming language in2004 as part ofJ2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." [ [http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html Java Programming Language] ]Hierarchy and classification
As per "JavaTM Language Specification" [ [http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html JavaTM 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.
*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 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 for generics
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an
ArrayList
of typeObject
. Then, it adds aString
to theArrayList
. Finally, it attempts to retrieve the addedString
and cast it to anInteger
.Although the code compiles without error, it throws a runtime exception (
java.lang.ClassCastException
) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.Utilizing generics, the above code fragment can be rewritten as follows:
The parameterized type
String
specified within the angle brackets declares anArrayList
of typeString
. With generics, it is no longer necessary to cast the third line to any particular type because the result ofv.get(0)
is defined asString
by the code generated by the compiler at compile-time.Compiling the third line of this fragment with J2SE 1.5 will yield a compile-time error because the compiler will detect that
v.get(0)
returnsString
instead ofInteger
. For a more elaborated example, see [http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf - Generics in the Java Programming Language] .Wildcards
Generic type parameters in Java are not limited to specific classes. Java allows the use of "wildcards" to specify bounds on the type of parameters a given generic object may have. Wildcards are type parameters of the form "?", possibly annotated with a bound. Given that the exact element type of an object with a wildcard is unknown, restrictions are placed on the type of methods that may be called on the object.
As an example of an unbounded wildcard,
List<?>
indicates a list which has an unknown object type. Methods which take such a list as an argument can take any type of list, regardless of parameter type. Reading from the list will return objects of typeObject
, and writing non-null elements to the list is not allowed, since the parameter type is not known.To specify the upper bound of a generic element, the
extends
keyword is used, which indicates that the generic type is a subtype of the bounding class. Thus it must either extend the class, or implement the interface of the bounding class. SoList<? extends Number>
means that the given list contains objects of some unknown type which extends theNumber
class. For example, the list could beList<Float>
orList<Number>
. Reading an element from the list will return aNumber
, while writing non-null elements is once again not allowed.The use of wildcards above are necessary since objects of one type parameter cannot be converted to objects of another parameter. Neither
List
norList
is a subtype of the other (even thoughFloat
is a subtype ofNumber
). So, code that deals withList
does not work withList
. (If it did, you would be able to insert aNumber
that is not aFloat
into it, which violates type safety.) The solution with wildcards works because it disallows operations that would violate type safety.To specify the lower bounding class of a generic element, the
super
keyword is used. This keyword indicates that the aforementioned generic type is a super-type of said bounding class. So,List<? super Number>
could representList<Number>
orList<Object>
. Reading from a list defined asList<? super Number>
returns elements of typeObject
. Writing to such a list requires elements of typeNumber
or its subclasses.Generic class definitions
Here is an example of a generic class:
This generic class can be used in the following way:
Generic method definitions
Here is an example of a generic method using the generic class above:
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:
Generics in throws clause
Although exceptions themselves can not be generic, generic parameters can appear in a throws clause:
Type erasure
Generics are checked at compile-time for type correctness. The generic type information is then removed via a process called type erasure. For example,
List<Integer>
will be converted to the raw type (non-generic type)List
, which can contain arbitrary objects. However, due to the compile-time check, the resulting code is guaranteed to be type correct, as long as the code generated no unchecked compiler warnings.As a result, there is no way to tell at runtime which type parameter is used on an object. For example, when you examine an
ArrayList
at runtime, there is no general way to tell whether it was anArrayList<Integer>
or anArrayList<Float>
. The exception to this is by usingReflection on existing list elements. However, if the list is empty or if its elements are subtypes of the parameterized type, even Reflection will not divulge the parameterized type.The following code demonstrates that the Class objects appear the same.
Java generics differ from
C++ templates. Java generics generate only one compiled version of a generic class or function regardless of the number of 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 erased from the compiled code. Consequently, one cannot instantiate a Java class of a parameterized type because instantiation requires a call to a constructor, which is not possible when the type is unknown at both compile-time and runtime.Because there is only one copy of a generic class, static variables are shared among all the instances of the class, regardless of their type parameter. As a result, the type parameter cannot be used in the declaration of static variables or in static methods. Static variables and static methods are "outside" of the scope of the class's parameterized types.
ee also
*
Generic programming
* Java
* Comparison of C# and Java
*Comparison of Java and C++ References
* [http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html Generics] by Sun Microsystems
* [http://homepages.inf.ed.ac.uk/wadler/fool/program/14.html Wild FJ] by Mads Torgersen, Erik Ernst, and Christian Plesner Hansen
* [http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html Java Generics FAQ] by Angelika Langer
* [http://www.javaworld.com/javaworld/jw-06-2004/jw-0607-tiger2.html Javaworld Taming the Tiger] Excellent overview.
Wikimedia Foundation. 2010.