Why doesn't Java allow for generic array creation? What difference does it make if it is allowed? If it is problematic then why type casting object array is not?
1 Answer
I think what you mean by "generic array" is Object[].
Well, it creates problems because when you initialize an array with size n, you allocate n identical blocks.
For instance:
Integer[] x = new Integer[10];
Allocates 10 blocks of 4 bytes = 40 bytes.
However,
Object[] x = new Object[10];
is ambiguous because it cannot be known if you're going to store Doubles, Strings or just custom objects you've created.
1 Comment
user2864740
This is incorrect. Integer and Object take up the same amount of "allocation" space. Only primitive types (eg.
int) behave differently from [all other] reference types. Java does not support the equivalent of C#'s value types.
Object[], which requires a cast on access. Simply avoid arrays directly when dealing with generics to avoid this - or, in the implementation, apply the appropriate cast from "known context".