Java Reference
In-Depth Information
To set an array list element to a new value, use the set method.
BankAccount anAccount = new BankAccount(1729);
accounts.set(2, anAccount);
This call sets position 2 of the
accounts
array list to
anAccount
, overwriting
whatever value was there before.
The set method can only overwrite existing values. It is different from the add
method, which adds a new object to the end of the array list.
You can also insert an object in the middle of an array list. The call
accounts.add(i, a)
adds the object a at position
i
and moves all elements by
one position, from the current element at position
i
to the last element in the array list.
293
294
Figure 3
Adding an Element in the Middle of an Array List.