0

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?

Dmitry
  • 115
  • 4
  • Your contract states that you have an Array of T, and you cast an Array of Object as an Array of T, when it could be an Array of anything. – Compass Nov 13 '18 at 18:21
  • @Compass i have a solution about creating the generic array - the way with setter works fine. i'm searching for the solution about the specified exception. i have no idea why it has been thrown. i'm know that generics in java have no specified type at compile time and all parameters substitudes to Object class. But string is a subtype of object, so the code should work... – Dmitry Nov 13 '18 at 18:29
  • Object, however is not a subclass of String. It is attempting to cast `names[0]` as a String reference with the value of null for assignment, but `names[0]` is an Object reference with the value of null, and cannot be cast to a String reference with a value of null. You have to cast it back to an Object array to do the assignment. `((Object[]) container.names)[0] = "foo";` – Compass Nov 13 '18 at 18:46
  • @Compass "It is attempting to cast names[0] as a String reference with the value of null" but when i'm using a setter the program also do the same casts, isn't it? why it works? – Dmitry Nov 13 '18 at 19:02
  • No. The generic class has [Type Erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). set is assigning Object to Object. – Compass Nov 13 '18 at 19:08

0 Answers0