//TestArrayList_toArray.java

import java.util.ArrayList;

public class TestArrayList_toArray
{
    public static void main(String[] args)
    {
        ArrayList<Integer> arrList = new ArrayList<Integer>();
        arrList.add(10);
        arrList.add(12);
        arrList.add(31);
        arrList.add(49);
        for (Integer i : arrList)
        {
            System.out.print(i + " ");
        }
        System.out.println();

        //toArray() copies ArrayList content into an array
        //The no-parameter version creates an array of Object of
        //the appropriate size and copies the ArrayList into it.
        //The version that takes an ArrayList parameter must copy
        //into an array whose size is at least that of the ArrayList
        //being copied.
        //Example 1
        //Note that the left-hand size is an (initially empty) array of Object.
        Object[] aObj = arrList.toArray();
        for (Object i : aObj)
        {
            System.out.print(i + " ");
        }
        System.out.println();

        //Example 2
        //Note that aInt1 is set to the same size as arrList.
        Integer aInt1[] = new Integer[arrList.size()];
        aInt1 = arrList.toArray(aInt1);
        for (int i : aInt1)
        {
            System.out.print(i + " ");
        }
        System.out.println();

        //Example 3
        //This time the array aInt2 is too small to hold arrList.
        //So a new array is created with size equal to that of arrList.
        Integer aInt2[] =
        {
            1, 2
        };
        aInt2 = arrList.toArray(aInt2);
        for (int i : aInt2)
        {
            System.out.print(i + " ");
        }
        System.out.println();

        //Example 4
        //This time the array aInt3 is larger than arrList.
        //In this case the value null is placed in the array
        //at the location following the last element from
        //arrList, which causes a NullPointEception to be
        //thrown when the array is displayed.
        Integer aInt3[] =
        {
            1, 2, 3, 4, 5, 6
        };
        aInt3 = arrList.toArray(aInt3);
        for (int i : aInt3)
        {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
/*  Output:
    10 12 31 49
    10 12 31 49
    10 12 31 49
    10 12 31 49
    10 12 31 49 Exception in thread "main" java.lang.NullPointerException
    at TestArrayList_toArray.main(TestArrayList_toArray.java:71)
*/
