0

When I create a single ArrayList, I create it as follows

ArrayList<Integer> al = new ArrayList<>();

When I create an array of ArrayList, I create it as follows

ArrayList<Integer>[] aal = new ArrayList[10];

My question is, why can't we specify the generics while creating an array, just like we do when creating an ArrayList. Why doesn't the following work to create an array of ArrayList

ArrayList<Integer>[] aal = new ArrayList<>()[10];
3
  • 2
    Array is structure which should guarantee type of its elements. Generics break that guarantee because they are erased at runtime. Commented Mar 18, 2017 at 19:10
  • Official tutorial abot this subject: docs.oracle.com/javase/tutorial/java/generics/… Commented Mar 18, 2017 at 19:13
  • 1
    This has been asked before too many times to count -- in the future, please search first. The usual solution is to not try to create an array of a generic collection but rather to instead create a collection of collections, such as a List of Lists, here List<List<Integer>>. Commented Mar 18, 2017 at 19:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.