I have this code,
class Test
{
public static void main(String args[])
{
ArrayList<Integer> al=new ArrayList<>();
al.add(1);
al.add(2);
al.add(3);
Integer a[]=new Integer[2];
al.toArray(a);
for(int i:a)
System.out.println(i);
/*for(int i=0;i<a.length;i++)
System.out.println(a[i]);*/
}
}
The above code throws NullPointerException but if I try to take the commented part off, and comment enhanced for loop it will print null 2 times. Printing a.length prints 2. Setting Integer array size to 3 will print 123.
Now correct me if I am wrong:
1> My understanding of toArray(T[] a) method is, if the size of the array is less than elements in the list, new array will be created with size specified by the array and elements in it will be null, considering this. my array should look like this a[]={null,null};
2> Difference between enhanced for loop and traditional for loop is that you can't modify or delete the individual element in enhanced for loop.
But, why is this different in this program? I am just printing them, why is enhanced for loop not printing null and throwing NullPointerException?