Java Generics – Why Generics Can’t Be in Arrays

genericsjavalanguage-design

Why is it that when I try to make an array of ArrayLists: ArrayList<Integer>[] arr=new ArrayList<Integer>[40]; there is an error and java does not allow this?

Is there a reason related to java's implementation of generics, generics in any language, or something arbitrary?

Best Answer

This is one of major holes in Java's generics, arrays are covariant, meaning that an array of type Foo[] is a subclass of Object[] and ParentOfFoo[]. Contrast this with List<Foo> which doesn't have this behavior.

This was important when Java didn't have generics (until Java 5) because otherwise, something like a generic sorting function was just impossible.

However it has this tricky problem that arrays like to know what type they are at runtime. However generics in Java is based on type erasure. These two things don't mesh well at all and that's where we get our problem.

So the long and short of it is, in Java 1, covariant arrays partially filled the hole that a lack of generics created. However when they tried to properly fill this hole, backwards compatibility meant that arrays were pretty impossible to implement.

In fact, the guy who actually created the framework for generics, Martin Odersky, talked about this here during an interview about why he made Scala. (Pretty fascinating if you are interested in Scala's history at all)