I have a class, which contains a wrapped parametrized array:
public class CatContainer <T> {
T[] names;
public CatContainer(){
names=(T[]) new Object[10];
}
void set(int index, T value){
names[index]=value;
}
}
And have corresponding client, where i'm using two ways to access the array.
CatContainer<String> cats=new CatContainer<>();
//cats.names[0]="Murzik";
//cats.set(0, "Murzik");
Can you explain me, why when i'm using a setter the programm works fine, but when i'm using the direct access cats.names[0]="Murzik"
the programm throws the Exception?
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
P.S. i have a solution about creating the generic array - the way with setter works fine. i'm searching for the explanation about the specified exception. i have no idea why it has been thrown when i'm using the direct access to the array. I know that generics in java have no specified type at run time and all parameters casts to Object type. But string is a subtype of object, so why the code is not working as expected?