Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java allow for the creation of generic arrays?

There are plenty of questions on stackoverflow from people who have attempted to create an array of generics like so:

ArrayList<Foo>[] poo = new ArrayList<Foo>[5];

And the answer of course is that the Java specification doesn't allow you to declare an array of generics.

My question however is why ? What is the technical reason underlying this restriction in the java language or java vm? It's a technical curiosity I've always wondered about.

like image 893
dreadwail Avatar asked Jun 07 '10 20:06

dreadwail


People also ask

Can generic arrays be created in Java?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.

How do you create a generic array of T in Java?

Notice how it makes use of Array#newInstance to build a new array, like in our previous stack example. We can also see that parameter a is used to provide a type to Array#newInstance. Finally, the result from Array#newInstance is cast to T[] to create a generic array.

What is not allowed with generics Java?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

Why should we avoid generics in Java?

Type Safety: Generics make errors to appear compile time than at run time (It's always better to know problems in your code at compile time rather than making your code fail at run time).


2 Answers

Arrays are reified - they retain type information at runtime.

Generics are a compile-time construct - the type information is lost at runtime. This was a deliberate decision to allow backward compatibility with pre-generics Java bytecode. The consequence is that you cannot create an array of generic type, because by the time the VM wants to create the array, it won't know what type to use.

like image 82
danben Avatar answered Sep 21 '22 06:09

danben


See Effective Java, Item 25.

like image 20
JRL Avatar answered Sep 20 '22 06:09

JRL