What I actually find a bit misleading, is that it says "joined at their hips". First I thought this would be a special feature of the java.util.Arrays.asList() method.
But they are only linked, because the example only uses a reference, and does not make a new e.g. ArrayList. The fact, that the changes are made both in the array and the list is not a result of using the asList method, but a result of using one object (the array) via two references.
Only to make this difference clear, I post some own code here:
First, the way the method was used in the K&B book:
As there is no ArrayList(LinkedList, whatsoever ...) object around, both - changes in the array as well as in the list - result in changes in both. So the output is:
[7, 2, 3, 4, 8] [7, 2, 3, 4, 8]
The last but one line is only for easier output.
This link comes only from addressing both with two references (array and list). It is not a feature of the Arrays.asList method as the following example shows:
Now they are independent and not joined at the hip. output is: [1, 2, 3, 4, 8] [7, 2, 3, 4, 5]
It's not the original java.util.ArrayList, it's inner-class from class Arrays. The inner-class ArrayList has custom get & set method, it's connecting to the array variables So when you change the content of array or list it'll change the same data. With this Arrays$ArrayList class you cannot add/remove, it'll give you java.lang.UnsupportedOperationException
But when you use :
It's a new Object, the original java.util.ArrayList class. And have no connection with the Array variables.
Maybe the book just not explicit say that the asList() method return a inner-class in class Arrays that declare like this
[ November 30, 2006: Message edited by: jimmy halim ]
Knowledge is power<br />My Blog : <a href="http://jimmod.blogspot.com/" target="_blank" rel="nofollow">http://jimmod.blogspot.com/</a>
subject: Doubt in K&B SCJP 5: topic Converting Arrays to Lists to Arrays