简体   繁体   中英

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.

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.

Here is an old blog post I wrote where I explain the problem: Java generics quirks

See How do I generically create objects and arrays? from Angelika Langer's Java Generics FAQ for a workaround (you can do it using reflection). That FAQ contains everything you ever want to know about Java generics.

You are forced to use

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

which will give you an unchecked warning. The reason is that there is a potential type safety issue with generics and the runtime type-checking behavior of Java arrays, and they want to make sure you are aware of this when you program. When you write new ArrayList[...] , you are creating something which will check, at runtime, everything that gets put into it to make sure that it is an instance of ArrayList . Following this scheme, when you do new ArrayList<Foo>[...] , then you expect to create something that checks at runtime everything that gets put into it to make sure it is an instance of ArrayList<Foo> . But this is impossible to do at runtime, because there is no generics info at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM