Generics in Java
From Seo Wiki - Search Engine Optimization and Programming Languages
| File:Wikibooks-logo-en-noslogan.svg | The Wikibook Java Programming has a page on the topic of
Generics </td>
</tr> </table> Generics are a facility of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety."[1]
[edit] Hierarchy and classificationAs per JavaTM Language Specification[2]:
[edit] Motivation for genericsThe following block of Java code illustrates a problem that exists when not using generics. First, it declares an List v = new ArrayList(); v.add("test"); Integer i = (Integer)v.get(0); Although the code compiles without error, it throws a runtime exception ( Using generics, the above code fragment can be rewritten as follows: List<String> v = new ArrayList<String>(); v.add("test"); Integer i = v.get(0); // (type error) The type parameter Compiling the third line of this fragment with J2SE 5.0 (or later) will yield a compile-time error because the compiler will detect that [edit] WildcardsGeneric 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, To specify the upper bound of a generic element, the The use of wildcards above are necessary since objects of one type parameter cannot be converted to objects of another parameter. Neither List<Integer> ints = new ArrayList<Integer>(); ints.add(2); List<Number> nums = ints; //valid if List<Number> is a supertype of List<Integer> according to substitution rule. nums.add(3.14); Integer x=ints.get(1); // now 3.14 is assigned to an Integer variable!
To specify the lower bounding class of a generic element, the [edit] Generic class definitionsHere is an example of a generic class: public class Pair<T, S>{ public Pair(T f, S s){ first = f; second = s; } public T getFirst(){ return first; } public S getSecond() { return second; } public String toString() { return "(" + first.toString() + ", " + second.toString() + ")"; } private final T first; private final S second; } This generic class can be used in the following way: Pair<String, String> grade440 = new Pair<String, String>("mike", "A"); Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100); System.out.println("grade:" + grade440.toString()); System.out.println("marks:" + marks440.toString()); [edit] Generic method definitionsHere is an example of a generic method using the generic class above: public <T> Pair<T,T> twice(T value) { return new Pair<T,T>(value,value); } In many cases the user of the method need not indicate the type parameters, as they can be inferred: Pair<String, String> pair = twice("Hello"); The parameters can be explicitly added if needed: Pair<String, String> pair = this.<String>twice("Hello"); [edit] Generics in throws clauseAlthough exceptions themselves cannot be generic, generic parameters can appear in a throws clause: public <T extends Throwable> void throwMeConditional (boolean conditional, T exception) throws T { if(conditional) throw exception; } [edit] Type erasureGenerics are checked at compile-time for type correctness. The generic type information is then removed via a process called type erasure. For example, As a result, there is no way to tell at runtime which type parameter is used on an object. For example, when an The following code demonstrates that the Class objects appear the same: ArrayList<Integer> li = new ArrayList<Integer>(); ArrayList<Float> lf = new ArrayList<Float>(); if (li.getClass() == lf.getClass()) // evaluates to true System.out.println("Equal"); 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. T instantiateElementType(List<T> arg) { return new T(); //causes a compile error } 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. [edit] See also[edit] References
[edit] External links
|