Let's start with question 2 first and then get back to question 1:
Question 2:
>
ArrayList[] pl2 = new ArrayList[10];
ArrayList[] pl3 = new ArrayList[10];
What is the difference as far as the reference declaration of p12 and
p13 is concerned?
In pl2 ensures better type safety than p13.
If I write for pl2:
pl2[0]=new ArrayList<String>();
it will give me a compiler error stating "cannot convert from ArrayList<String>
to ArrayList<Integer>
"
Thus it ensures compile time safety.
However if I write for p13
pl3[0]=new ArrayList<String>();
pl3[1]=new ArrayList<Integer>();
it will not throw any error and the onus will be on the developer to code and check properly while extracting data from p13, to avoid any unsafe type conversion during runtime.
Question 1:
That's just probably the way generics work. During the main array initialization, ArrayList<Integer>[] pl2 = new ArrayList[10]
, the left hand side, ArrayList<Integer>[] pl2
, will ensure type safety only when you initialize the ArrayList object in the index position:
pl2[0]=new ArrayList<Integer>();
The right hand side main array declaration = new ArrayList[10]
just ensures that the index position will hold ArrayList type items. Also have a look at type erasure concepts in Type Erasure for more information.