Page 447 - Introduction to Programming with Java: A Problem Solving Approach
P. 447
Figure 10.25 API headings and descriptions for some additional ArrayList methods
Survivor Example
To reinforce what you’ve learned so far, let’s take a look at how an ArrayList class is used in a complete working program. See the Survivor5 program in Figure 10.26. It creates a list of survivor tribesmen by in- stantiating an ArrayList object and calling add to append tribesmen to the list. It then randomly chooses one of the tribesmen and removes that tribe member from the list. It prints a sorry message for the removed tribe member and a remaining message for the remaining tribesmen.
Note the format of the tribesmen in Figure 10.26’s bottom output line—square brackets surround- ing a comma-separated list. Can you find the Survivor code that prints that list? If you’re looking for square brackets and a loop, forget it, they’re not there. So how in the world does the square-bracketed list get printed? In the final println statement at the bottom of the program, the tribe ArrayList gets concatenated to a string. That causes the JVM to do some work behind the scenes. If you attempt to concat- enate an ArrayList with a string or print an ArrayList, the ArrayList returns a comma-separated list of ArrayList elements surrounded by square brackets ([]). And that’s exactly what happens when Figure 10.26’s last statement executes.
10.11 TheArrayListClass 413
public void add(int index, E elem)
Starting with the specified index position, the add method shifts the original elements at and above the index position to next-higher-indexed positions. It then inserts the elem parameter at the specified index position.
public int indexOf(Object elem)
Searches for the first occurrence of the elem parameter within the list and returns the index position of the found element. If the element is not found, the indexOf method returns -1.
public boolean isEmpty()
Returns true if the ArrayList contains no elements. public int lastIndexOf(Object elem)
Searches for the last occurrence of the elem parameter within the list and returns the index position of the found element. If the element is not found, the indexOf method returns -1.
public E remove(int index)
Removes and returns the element at the specified index position. To handle the removed element’s absence, the remove method shifts all higher-indexed elements by one position to lower-indexed positions.
public int size()
Returns the number of elements currently in the ArrayList. Apago PDF Enhancer
5 Survivor is a trademark of CBS Broadcasting Inc.