Java Reference
In-Depth Information
The call on add instructs the computer to insert the new String at index 1.
Therefore, the old value at index 1 and everything that follows it gets shifted to the
right. So, the code produces the following output:
before list = [Tool, Phish, Pink Floyd]
after list = [Tool, U2, Phish, Pink Floyd]
ArrayList also has a method for removing a value at a particular index. The
remove method also preserves the order of the list by shifting values to the left to fill
in any gap. For example, consider what happens to the previous list if we remove the
value at position 0 and then remove the value at position 1:
System.out.println("before remove list = " + list);
list.remove(0);
list.remove(1);
System.out.println("after remove list = " + list);
This code produces the following output:
before remove list = [Tool, U2, Phish, Pink Floyd]
after remove list = [U2, Pink Floyd]
This result is a little surprising. We asked the list to remove the value at position 0
and then to remove the value at position 1. You might imagine that this would get rid
of the String s " Tool " and " U2 " , since they were at positions 0 and 1, respectively,
before this code was executed. However, an ArrayList is a dynamic structure whose
values move around and shift into new positions in response to your commands. The
order of events is demonstrated more clearly if we include a second println state-
ment in the code:
System.out.println("before remove list = " + list);
list.remove(0);
System.out.println("after 1st remove list = " + list);
list.remove(1);
System.out.println("after 2nd remove list = " + list);
This code produces the following output:
before remove list = [Tool, U2, Phish, Pink Floyd]
after 1st remove list = [U2, Phish, Pink Floyd]
after 2nd remove list = [U2, Pink Floyd]
The first call on remove removes the String "Tool" because it's the value cur-
rently in position 0. But once that value has been removed, everything else shifts
over: The String "U2" moves to the front (to position 0), the String "Phish" shifts
into position 1, and the String "Pink Floyd" moves into position 2. So, when the
 
Search WWH ::




Custom Search