-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?

Paritosh Pandey
  • 157
  • 1
  • 4
  • 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". – user2864740 Jan 05 '15 at 19:26
  • It does. You're free to do this: Object [] putAnyTypeHere = new Object[10]; – duffymo Jan 05 '15 at 19:26
  • 1
    [Type Erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html). – Elliott Frisch Jan 05 '15 at 19:27

1 Answers1

-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.

padawan
  • 1,277
  • 1
  • 16
  • 43
  • 1
    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. – user2864740 Jan 05 '15 at 19:30