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.
No comments:
Post a Comment