1

I was reading java docs

https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays

It says

"You cannot create arrays of parameterized types"

So I'm able to create below array of ArrayList using below code

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

But why its showing error on below code. Its also an array of Lists. Why its showing compile time error ?

List<Integer>[] arrayOfLists = new List<Integer>[2];

WHat's parameterized type here actually .? I think its Integer, but its present in both types of arrays.

drill
  • 134
  • 1
  • 12
  • 1
    Your first example is a **raw type**; and thus bypasses Java generic type checking entirely. – Elliott Frisch Feb 03 '20 at 05:20
  • @ElliottFrisch, What's not a raw type in second example ..? – drill Feb 03 '20 at 05:21
  • `List` is a parameterized interface which still counts as a parameterized type. – Powerlord Feb 03 '20 at 05:29
  • The generic type declaration on the right hand side (the bit in diamond brackets - `List` in your example). Java uses type erasure at runtime for generics, so at runtime it doesn't know that arrayOfLists is meant to only contain Lists of `List` type. – stringy05 Feb 03 '20 at 05:30
  • @stringy05, On right hand side if I do like this new List[2]; it allows but what about left hand side, generic type is still mentioned there ...? Dont you think its syntactically wrong ? – drill Feb 03 '20 at 05:32
  • It's the difference between a compile time error and a run time error; see also [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/2970947) – Elliott Frisch Feb 03 '20 at 05:45

0 Answers0