Shashwat
Shashwat

Reputation: 449

Why is it legal to cast an Object array to a generics array?

When I try to cast an object array to a custom data-type (class) array I get the ClassCastException but when I cast an object array to a generics array, no such error is observed; furthermore, if I pass a custom data-type(class) as a type argument, the ClassCastException is not thrown either.

I experimented several things:

The entire Main class for further reference (assume TestClass is defined):

public class Main<Item>{
    Item a[];
    TestClass b[];
    public Main(){
        //this.b = (TestClass[]) new Object[100]; (errors disappear when this line is commented out, otherwise ClassCastException is thrown)
        this.a = (Item[]) new Object[100];
    }
    public void doStuff(){
        System.out.println(Arrays.toString(this.a));
        System.out.println(Arrays.toString(this.b));
    }
    public static void main(String[] args) {
        Object a = new Object();
        Main<TestClass> m = new Main<TestClass>(); //TestClass passed as type argument, should cause problems in the constructor
        m.doStuff();
    }

Apologies for not using proper Java conventions, I was only experimenting :)

Upvotes: 1

Views: 74

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170815

Because of type erasure: Item is erased to Object, so your code becomes

public class Main {
    Object a[];

    ...
    this.a = (Object[]) new Object[100];
    ...
}

Unsurprisingly that cast succeeds.

Now if you add e.g.

TestClass[] b = m.a;

to main, the compiler will need to insert a cast

TestClass[] b = (TestClass[]) m.a;

and that will fail because m.a is really an Object[].

Upvotes: 2

Related Questions