Source of TestArrayList_toArray.java


  1: //TestArrayList_toArray.java

  3: import java.util.ArrayList;

  5: public class TestArrayList_toArray
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         ArrayList<Integer> arrList = new ArrayList<Integer>();
 10:         arrList.add(10);
 11:         arrList.add(12);
 12:         arrList.add(31);
 13:         arrList.add(49);
 14:         for (Integer i : arrList)
 15:         {
 16:             System.out.print(i + " ");
 17:         }
 18:         System.out.println();

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

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

 45:         //Example 3
 46:         //This time the array aInt2 is too small to hold arrList.
 47:         //So a new array is created with size equal to that of arrList.
 48:         Integer aInt2[] =
 49:         {
 50:             1, 2
 51:         };
 52:         aInt2 = arrList.toArray(aInt2);
 53:         for (int i : aInt2)
 54:         {
 55:             System.out.print(i + " ");
 56:         }
 57:         System.out.println();

 59:         //Example 4
 60:         //This time the array aInt3 is larger than arrList.
 61:         //In this case the value null is placed in the array
 62:         //at the location following the last element from
 63:         //arrList, which causes a NullPointEception to be
 64:         //thrown when the array is displayed.
 65:         Integer aInt3[] =
 66:         {
 67:             1, 2, 3, 4, 5, 6
 68:         };
 69:         aInt3 = arrList.toArray(aInt3);
 70:         for (int i : aInt3)
 71:         {
 72:             System.out.print(i + " ");
 73:         }
 74:         System.out.println();
 75:     }
 76: }
 77: /*  Output:
 78:     10 12 31 49
 79:     10 12 31 49
 80:     10 12 31 49
 81:     10 12 31 49
 82:     10 12 31 49 Exception in thread "main" java.lang.NullPointerException
 83:     at TestArrayList_toArray.main(TestArrayList_toArray.java:71)
 84: */