Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 13 down vote accepted

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 your interested in Scala's history at all)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.