public class TestLinkedList_toArray
1: //TestLinkedList_toArray.java
3: import java.util.LinkedList;
5: public class TestLinkedList_toArray
6: {
7: public static void main(String[] args)
8: {
9: LinkedList<Integer> arrList = new LinkedList<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 LinkedList content into an array
21: //The no-parameter version creates an array of Object of
22: //the appropriate size and copies the LinkedList into it.
23: //The version that takes an LinkedList parameter must copy
24: //into an array whose size is at least that of the LinkedList
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[] = { 1, 2 };
49: aInt2 = arrList.toArray(aInt2);
50: for (int i : aInt2)
51: {
52: System.out.print(i + " ");
53: }
54: System.out.println();
56: //Example 4
57: //This time the array aInt3 is larger than arrList.
58: //In this case the value null is placed in the array
59: //at the location following the last element from
60: //arrList, which causes a NullPointEception to be
61: //thrown when the array is displayed.
62: Integer aInt3[] = { 1, 2, 3, 4, 5, 6 };
63: aInt3 = arrList.toArray(aInt3);
64: for (int i : aInt3)
65: {
66: System.out.print(i + " ");
67: }
68: System.out.println();
69: }
70: }
71: /* Output:
72: 10 12 31 49
73: 10 12 31 49
74: 10 12 31 49
75: 10 12 31 49
76: 10 12 31 49 Exception in thread "main" java.lang.NullPointerException
77: at TestLinkedList_toArray.main(TestLinkedList_toArray.java:70)
78: */