ArrayLists and Iterators
12. Setting ArrayList Elements
Answer:
size: 0
new size: 3
element 0: Amy
element 1: Bob
element 2: Cindy
Setting ArrayList
Elements
ArrayList
Elements
The add(E elt)
method adds to the end of an ArrayList
. But sometimes you want to change the element at a particular index.
set( int index, E elt )
The element previously at index
is replaced with the reference elt
. The index
should be in the range 0 to size-1.
An IndexOutOfBoundsException
is thrown if the index is out of bounds. (For now, this means that the program will halt.)
The index must be in the range 0 to size-1, which are the indexes of cells already occupied. This method can't "skip over" empty cells when it adds an element. It can't be used to make a list that has gaps in it.
The program first builds a list of three elements, then replaces the element at index zero.
|
Question 12: