I am trying to create an array of the generic class “DataStruct”.
The code is the following:
public class DataArray<T> {
DataStruct<T>[] array;
int index;
public DataArray(int capacity) {
array = (DataStruct<T>[]) new Object[capacity]; // !!!
this.index = 0;
}
}
I get a java.lang.ClassCastException (Ljava.lang.Object; cannot be cast to [LArrayBased.DataStruct;) at the line marked with three exclamation marksat the end, while testing it.
Can you please tell me the correct way to create it?
Why not declare
Object[]can not be cast toDataStruct[].Because arrays are refiable in nature that means arrays know their type at runtime so If you convert it to
Object []like below you will again run in to problemsSo it is wise to declare it as
DataStruct[capacity]