3

I'm creating an array of ArrayLists using the following code:

ArrayList<Integer>[] list = new ArrayList[n];

As it is said that array of generics is not allowed. How is that my code compiles?

  • My question is that even though people say that generic arrays are not allowed in java why is this code compiling for me: `ArrayList[] list = new ArrayList[n];` – Shubham Urkade Dec 13 '18 at 06:56
  • 2
    Because you aren't using full generics in that case; `new ArrayList[n]` is using the _raw type_ of `ArrayList`. The compiler should be emitting a warning saying that code is unsafe/unchecked. It's similar to casting a raw type to a generic type—it's allowed but isn't safe. – Slaw Dec 13 '18 at 06:59

2 Answers2

2

Because you are initializing an array not the ArrayList Look at this:

ElementType [] name = new ElementType[size];

Here your element type is ArrayList

Look at this site:Array of ArrayList

A.Najafi
  • 390
  • 8
  • 16
0

refer java documentation here. You cannot create arrays of parameterized types. if it were allowed you can then create generic lists which each element of a different type. That is just not allowed. The documentation explains this well

Vasanth Raghavan
  • 154
  • 3
  • 12