3

Java does not allow to create array of collections, shows compilation error cannot create a generic array

ArrayList<String>[] list = new ArrayList<String>[2];

but i can create generic collection like this

ArrayList<?>[] list = new ArrayList<?>[2];

Why there is no compiler warning in the above case

ravthiru
  • 8,878
  • 2
  • 43
  • 52

1 Answers1

1

In Java you can't create a generic array. I think the reason why this isn't allowed is because arrays are reified which means that the type information is known at runtime and is enforced by them. By contrast, the type information from generics is erased at runtime.

Because of the above, it's allowed to have something like this T[] array = new E[size]; where E is a subtype of T.

When you use generics you aren't allowed to do something like this: List<T> list = new ArrayList<E>(); where E is a subtype of T.

The only allowed type parrameter allowed with arrays is the unbound wildcard ? since this means that any type is accepted.

Slimu
  • 2,301
  • 1
  • 22
  • 28