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?

2
  • My question is that even though people say that generic arrays are not allowed in java why is this code compiling for me: ArrayList<Integer>[] list = new ArrayList[n]; Commented Dec 13, 2018 at 6: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. Commented Dec 13, 2018 at 6:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.