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?
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[].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With