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];
saltmangotree
  • 171
  • 2
  • 11
  • 2
    Array is structure which should *guarantee* type of its elements. Generics break that guarantee because they are erased at runtime. – Pshemo Mar 18 '17 at 19:10
  • Official tutorial abot this subject: https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays – Pshemo Mar 18 '17 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>`. – Hovercraft Full Of Eels Mar 18 '17 at 19:14

0 Answers0