Wednesday, December 29, 2010

Raw references to Generic types erases Generic information

When you use a raw (without type parameter) reference to a generic type all generic information for that instance is lost. When I say all information is lost, I mean all instance member’s (fields, methods) get un-generic semantic (The compiler treats them as if no generic information exists at all, it somehow erases that information) even the generic information not related to the generic type we are using. See the following example that can be surprising, as it doesn’t even use the generic type parameter (T):



import java.util.ArrayList;
import java.util.List;
public class Generic<T>{
    public List<String> getStringList() {
        List<String> list = new ArrayList<String>();
        list.add("hola");
        list.add("ciao");
        return list;
    }
    public static void main(String[]args){
        Generic gen=new Generic<Object>();
        for(String string:gen.getStringList()){
            System.out.println(string);
        }
    }
}






The code doesn’t even compile!!. By using the raw reference in the line

Generic gen=new Generic<Object>;

the compiler is somehow erasing the generic information from the getStringList method, meaning that now the expected return type of the getStringList is simply List. So, you get the compiler error:

Type mismatch: cannot convert from element type Object to String in the for loop.
.......................
Quick Java Facts
Top Java books...

No comments:

Post a Comment