Page 444 - Introduction to Programming with Java: A Problem Solving Approach
P. 444

                410 Chapter 10 Arrays and ArrayLists
Besides the angled brackets, there are two additional noteworthy items in the above example. First, there is no size specification. That’s because ArrayList objects start out with no elements and they au- tomatically expand to accommodate however many elements are added to them. Second, the element type, Student, is a class name. For ArrayLists, you must specify a class name, not a primitive type, for the element type. Specifying a class name means that ArrayLists can hold only references to objects. They cannot hold primitives, like int or double. That’s technically true, but there’s an easy way to mimic stor- ing primitives in an ArrayList. We’ll discuss how to do that in the next section.
Adding Elements to an ArrayList
To convert an instantiated empty ArrayList into something useful, you need to add elements to it. To add
an element to the end of an ArrayList, use this syntax: ArrayList-reference-variable.add(item);
The item that’s added must be the same type as the element type specified in the ArrayList’s declaration. Perhaps the simplest type of element object is a string, so let’s start with an ArrayList of strings. Suppose you want to write a code fragment that creates this ArrayList object:
colors 0
1
2
            Apago PDF Enhancer
Try writing the code on your own before proceeding. When you’re done, compare your answer to this:
import java.util.ArrayList;
.. .
ArrayList<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("blue");
The order in which you add elements determines the elements’ positions. Since we added “red” first, it’s at index position 0. Since we added “green” next, it’s at index position 1. Likewise, “blue” is at index position 2.
API Headings
In describing the ArrayList class, we’ll use API headings to present the ArrayList class’s methods. As you may recall from Chapter 5, API stands for application programming interface, and API headings are the source code headings for the methods and constructors in Sun’s library of pre-built Java classes. The API headings tell you how to use the methods and constructors by showing you their parameters and return types. For example, here’s the API heading for the Math class’s pow method:
public static double pow(double num, double power)
The above line tells you everything you need to know to use the pow method. To call the pow method, pass in two double arguments: one argument for the base and one argument for the power. The static modifier tells you to preface the call with the class name and then a dot. The double return value tells you
 “red”
 “green”
 “blue”










































































   442   443   444   445   446