So, lets get started!!!
Converting Arrays to Lists and Lists to Arrays
There are a couple of methods that allow you to convert arrays to Lists, and Lists to arrays. The List and Set classes have toArray() methods, and the Arrays class has a method called asList().
The Arrays.asList() method copies an array into a List. The API says, “Returns a fixed-size list backed by the specified array” When you use the asList() method, the array and the List become joined at the hip. When you update one of them, the other gets updated automatically. Let’s look at an example:
String[] sa = {"one", "two", "three", "four"};
List sList = Arrays.asList(sa); // make a List
System.out.println("size " + sList.size());
System.out.println("idx2 " + sList.get(2));
sList.set(3,"six"); // change List
sa[1] = "five"; // change array
for(String s : sa)
System.out.print(s + " ");
System.out.println("\nsl[1] " + sList.get(1));
This produces
size 4
idx2 three
one five three six
sl[1] five
Notice that when we print the final state of the array and the List, they have both been updated with each other’s changes.
Now let’s take a look at the toArray() method. There’s nothing fancy going on with the toArray() method; it comes in two flavors: one that returns a new Object array, and one that uses the array you send it as the destination array:
List
for(int x=0; x<3; x++) iL.add(x); Object[] oa = iL.toArray(); // create an Object array Integer[] ia2 = new Integer[3]; ia2 = iL.toArray(ia2); // create an Integer array This is or rather this was a straight forward topic and you can expect one or two questions related to this in the exam. So, just because this is a miniscule topic, don't ignore it :-) Previous Chapter: Chapter 42 - Searching Arrays and Collections
Next Chapter: Chapter 44 - Using Lists

I run the code, and the result is actually:
ReplyDeletesize 4
idx2 three
one five three six
sl[1] five
I think there is something wrong the statement "Notice that when we print the final state of the array and the List, they have both been updated with each other’s changes."
Hi Anonymous
ReplyDeleteThe statement is correct.
System.out.print(s + " ");
System.out.println("");
System.out.println(sList);
Try replacing the last two lines with the above three lines. you will see below:
one five three six
[one, five, three, six]
The value updated in the Array is reflecting in the List and vice versa.
Hope this clarifies.
Anand.