-1

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?

3
  • This is an implementation artifact of arrays - which store the type of element in the type - and generics which don't know the concrete type and are "erased". Thus all generic arrays are 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". Commented Jan 5, 2015 at 19:26
  • It does. You're free to do this: Object [] putAnyTypeHere = new Object[10]; Commented Jan 5, 2015 at 19:26
  • 1
    Type Erasure. Commented Jan 5, 2015 at 19:27

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.