I'm very new to generic programming in Java.
I don't understand why arrays of generic type can't be created.
T[] a = new T[size]; //why does this give an error?
If generic type means that the generic placeholder T
will be replaced by a class name during run-time, what prevents us from creating an array having generic references?
After a bit of searching, I found a workaround
T[] a = (T[])new Object[size]; //I don't get how this works?
Although I found a solution, I still fail to understand what prevents from creating a generic array.
Suppose I create a function that returns an Object array.
public Object[] foo(){
return new Object[12];
}
And then make the call
String[] a = (String[])foo();
gives a ClassCastException
. But why?
Doesn't it look similar to first line of code where I cast Object array into T array?
T[] a = (T[])new Object[size];
If this went without a glitch why didn't that?