The oracle doc says Generics are implemented in java using a technique call type erasure and this is how it works.
- Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
- Insert type casts if necessary to preserve type safety.
- Generate bridge methods to preserve polymorphism in extended generic types.
So if I have a Generic class say Container as below:
class Container<T>{
T initialValue;
List<T> valueList=new ArrayList<T>();
public List<T> getValueList(){
return valueList;
}
}
it's equivalent class would look like after being processed by type erasure:
class Container{
Object initialValue;
List valueList=new ArrayList();
public List getValueList(){
return valueList;
}
}
Correct me if a wrong here
Similarly, if a modify the above class as below
class Container<T>{
T initialValue;
List<T> valueList=new ArrayList<T>();
T[] arrayValue;
public Container(T[] array){
arrayValue=array;
}
public List<T> getValueList(){
return valueList;
}
}
won't be this equivalent to???
class Container{
Object initialValue;
List valueList=new ArrayList();
Object[] arrayValue;
public Container(Object[] array){
arrayValue=array;
}
public List getValueList(){
return valueList;
}
}
if this is true then I should also have like this:
T[] arrayValue=new T[10];//Compile time error;
as the above statement would get converted into
Object[] arrayValue=new Object[10];
Need clarity on how type erasure works for Arrays in Java??