I know Java does not allow not Create Instances of Type Parameters. Many articles simply said "Type Erase" as the reason. But does type parameters initialization not occur before type erase? Is Type Erase the only reason? Here is a example:
public class GenObj {
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
public static main(){
List<String> list= new ArrayList<String>();
GenOjb.append<String>(list);
}
}
When we call the generic method using GenOjb.append(list), I think the compiler will replace E in the method with String first and then do "Type Erase", is that correct? If so, as long as we have a way to ensure E does indeed have a default constructor, we should be able to create instance of type parameters. Can someone explain in more detail why Java does not allow creating instance of parameter type? Thanks.