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?
StringandItemare not in the same line.new GenericStack<String>(10)works but if you tryString[] stra = new GenericStack<String>(10).getData();(implement the corresponding getter), it fails with the ClassCastException. So it does not "really" work, the cast has not been done magically.Array.newInstance(Class clazz, Integer)to generically create your array. ExampleArray.newInstance(String.class, sz).