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?
String
andItem
are not in the same line. – Dukeling Jun 14 '13 at 12:34new 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. – Arnaud Denoyelle Jun 14 '13 at 12:38Array.newInstance(Class clazz, Integer)
to generically create your array. ExampleArray.newInstance(String.class, sz)
. – Arnaud Denoyelle Jun 14 '13 at 12:41