I have an immutable class , with the following layout ,
public final class A <T> {
private ArrayList<T> myList;
private A(){
myList = new ArrayList<T>();
}
public A<T> addData(T t){
A newOb = // make a new list and instantiate using overloaded constructor
T newT = new T(); ***********ERROR HERE*************
newOb.myList.add(newT);
return newOb;
}
.........
}
The error that I get here is cannot instantiate type T . Now , I think this is related to maybe type erasure in Java.
How can I overcome this ? I want to add a new copy of the argument that is being passed to addData into my list.
In java language generics are implemented by erasure, so it is impossible to instantiate a generic type. Also it is impossible to instiate an array of generic type and so on.
You can try to use
Cloneableinterface as a type bound or add your own similar interface.