Monday, October 1, 2012

Generics aren't so generic !

Generics in Java 5 enables Types(class/interface) to  have parameters when defining classes, interfaces and methods.A generic type is a type with formal type parameters. While A parameterized type is an instantiation of a generic type with actual type arguments.

A generic type is a reference type that has one or more type parameters. These type parameters are later replaced by type arguments when the generic type is instantiated (or declared )

If the compiler erases all type parameters at compile time, why should you use generics?

1) To provide compile time casting.
2) Elimination of casts
3) Enabling programmers to implement generic algorithms. ..( more later )

******UpperBound WildCards
ex:
List <  ? extends Number >

take method
public static double sumOfList(List < ? extends Number > list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}


here both
List < Integer >  li = Arrays.asList(1, 2, 3);
List < Double > li = Arrays.asList(1.1, 2.1, 3.1); 
can substitute at compile time.


******LowerBound WildCards 


public static void addNumbers(List < ? super Integer > list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}
 
Here only  
List < Integer > li = Arrays.asList(1, 2, 3);
or List < Number > li = Arrays.asList(1, 2, 3); 
can be passed at compile time.
Since Integer or any of its super class is allowed .

More explanation on Generic Types is given at

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

No comments: