Pages

Monday 16 April 2012

Java Generics


Previous Code :  
// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
      if (((String) i.next()).length() == 4)
        i.remove();

Disadvantage of this approach : 
When we declare c to be of type Collection<String>, this tells us
something about the variable c that holds true wherever and whenever
it is used, and the compiler guarantees it (assuming the program compiles
without warnings).
 
New Code :
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); )
      if (i.next().length() == 4)
        i.remove();
}
 
Advantages of this approach :  
A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks
whether the programmer is right only at run time.
 
Defining Simple Generics : 
public interface List<E> { void add(E x);
Iterator<E> iterator();
}public interface Iterator<E> { E next();
boolean hasNext();
}

You might imagine that List<Integer> stands for a version of List where E has
been uniformly replaced by Integer:
public interface IntegerList { void add(Integer x)
Iterator<Integer> iterator();
}
 
This might be misleading. 

Type parameters are analogous to the ordinary parameters used in methods or constructors.
Much like a method has formal value parameters that describe the kinds of
values it operates on, a generic declaration has formal type parameters. When a method
is invoked, actual arguments are substituted for the formal parameters, and the method
body is evaluated. When a generic declaration is invoked, the actual type arguments
are substituted for the formal type parameters.

Generic Subtyping : 
If Foo is a subtype (subclass or subinterface) of Bar, and G is some
generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.




Best Resources :
1) http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.pdf
2) http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html
3) http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html

Tip :
Generics was introduced in Java 1.5.

No comments:

Post a Comment