Page 445 - Introduction to Programming with Java: A Problem Solving Approach
P. 445
10.11 TheArrayListClass 411 to embed the method call in a place that can use a double value. Here’s an example that calculates the
volume of a sphere:
double volume = 1.333333333 * Math.PI * Math.pow(radius, 3)
How to Access Elements in an ArrayList
With standard arrays, you use square brackets to read and update an element. But with an ArrayList you don’t use square brackets. Instead, you use a get method to read an element’s value and a set method to update an element’s value.
Here’s the API heading for the ArrayList’s get method:
public E get(int index)
The index parameter specifies the position of the desired element within the ArrayList calling object. For example, the following method call retrieves the second element in a colors ArrayList:
colors.get(1);
If the index parameter refers to a nonexistent element, then a runtime error occurs. For example, if colors contains three elements, then this generates a runtime error:
colors.get(3);
In the get method’s API heading, note the E return type: public E get(int index)
The E stands for “elementA.”pIt raepgresoentsPtheDdaFta tyEpenofhthae AnrrcayeLrist’s elements, whatever that data type happens to be. So if an ArrayList is declared to have string elements, then the get method returns a string value, and if an ArrayList is declared to have Student elements, then the get method returns a Student value. The E in the get method’s heading is a generic name for an element type. Using a ge- neric name for a type is an important concept that will come up again with other methods. It’s important enough to justify a pedagogical analogy.
Using a generic return type is like saying you’re going to the grocery store to get “food.” It’s better to
use a generic term like food rather than a specific term like broccoli. Why? Because you might end up get-
ting Princess Fruit Chews at the store instead of broccoli. By specifying generic food as your “return type,”
4
Using a generic name for a type is possible with ArrayLists because the ArrayList class is de-
you’re free to get Princess Fruit Chews rather than broccoli, as your preschooler sees fit.
fined to be a generic class, by using <E> in its class heading: public class ArrayList<E>
You don’t need to understand generic class details in order to use ArrayLists, but if you want such de- tails, visit http://java.sun.com/docs/books/tutorial/java/generics/index.html.
How to Update an ArrayList Element
Now for the get method’s partner, the set method. The set method allows you to assign a value to an
ArrayList element. Here is the API heading for ArrayList’s set method: public E set(int index, E elem)
4 This analogy is taken from the real-life adventures of preschooler Jordan Dean.