What's the reason I can't create generic array types in Java?

devoured elysium picture devoured elysium · May 28, 2010 · Viewed 174.2k times · Source

What's the reason why Java doesn't allow us to do

private T[] elements = new T[initialCapacity];

I could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time can have different sizes, but in Java all kinds of T will be object references, thus having the same size (correct me if I'm wrong).

What is the reason?

Answer

newacct picture newacct · May 28, 2010

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.