public class TestArrayToList
1: //TestArrayToList.java
2: //Illustrates the conversion of an array to a list and
3: //(if you perform the actions suggested in the comments
4: //at the end) also shows why we should use the generic
5: //versions of containers such as lists (for safety reasons).
6: //Note use of the List interface as a type.
7: //Note also the default output format of a list of values.
9: import java.util.Arrays;
10: import java.util.List;
12: public class TestArrayToList
13: {
14: public static void main(String args[])
15: {
16: System.out.println();
18: //Create an array of integers and convert it to a list
19: Integer integerArray[] =
20: {
21: 2, 4, 6, 8
22: };
23: List<Integer> integerList = Arrays.asList(integerArray);
24: System.out.println("integerList contains these values: "
25: + integerList);
26: System.out.println("And its type is: "
27: + integerList.getClass().getName());
28: System.out.println();
30: //Create an array of strings and convert it to a list
31: String stringArray[] =
32: {
33: "klm", "abc", "xyz", "pqr"
34: };
35: List<String> stringList = Arrays.asList(stringArray);
36: System.out.println
37: (
38: "stringList contains these values: "
39: + stringList
40: );
41: System.out.println
42: (
43: "And its type is: "
44: + stringList.getClass().getName()
45: );
46: System.out.println();
47: }
48: }
49: /* Output:
51: integerList contains these values: [2, 4, 6, 8]
52: And its type is: java.util.Arrays$ArrayList
54: stringList contains these values: [klm, abc, xyz, pqr]
55: And its type is: java.util.Arrays$ArrayList
57: */
59: /*
60: Try the following:
61: First, insert the following assignment as the last line of code:
62: integerList = stringList;
63: Then try compiling to show that it does not compile.
65: But now ...
66: Use the "raw" List type for integerList and stringList.
67: Then recompile and run to show that everything still works.
68: Next, once again, insert the following assignment as the last line of code:
69: integerList = stringList;
70: Once more, try compiling to show that this time it does compile.
71: Then add the following line of code, compile/run and explain the output:
72: System.out.println("The list is: " + integerList);
73: */