Robert
Robert

Reputation: 197

How can I get rid of this ClassCastException? (java)

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?

Upvotes: 2

Views: 141

Answers (1)

Amit Deshpande
Amit Deshpande

Reputation: 19185

Why not declare

array = new DataStruct[capacity];

Object[] can not be cast to DataStruct[].

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 problems

Object[] array = new DataStruct[capacity]; 
array[0] = 10;//Array Store exception

So it is wise to declare it as DataStruct[capacity]

Upvotes: 6

Related Questions