Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting Object[] to a reference type array in java

In implementation of a generic stack ,the following idiom is used and works without any problem

public class GenericStack<Item> {
    private int N;
    private Item[] data;    

    public GenericStack(int sz) {
        super();
        data = (Item[]) new Object[sz];

    }
        ...
}

However when I try the following ,it causes a ClassCastException

String[] stra = (String[]) new Object[4];

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

How do you explain this?

like image 844
damon Avatar asked Jun 14 '13 12:06

damon


1 Answers

Casting a new Object[4] to a String[] doesn't work because an Object[] isn't a String[], just like an Object isn't a String.

The first example works because of type erasure. At runtime, the type parameterItem has been erased to Object. However it would similarly fail if you tried to assign the array to a reifiable type, for example if data wasn't private:

String[] strings = new GenericStack<String>(42).data;

This would similarly throw a ClassCastException, because what is actually an Object[] would be cast to String[].

like image 136
Paul Bellora Avatar answered Sep 21 '22 16:09

Paul Bellora