This book is now obsolete Please use CSAwesome instead.
9.7. The ArrayList Class¶
Luckily Java has a class that handles when you run out of room in an array and want to add more items to it or when the amount of space reserved for an array is much larger than what you actually need. It is called ArrayList. It implements the
List interface using an array and allows the underlying array to grow or shrink as needed. This also means that the
ArrayList class contains the code for the methods defined in the
Java actually has several classes that implement the
List interface (provide method bodies for the abstract methods defined in the interface). These are just some of the classes that implement the
Vector. You only need to learn about the
ArrayList class for the exam.
9.8. The Import Statement¶
List interface and
ArrayList class are both in the
java.util package. A package is a set of related classes. If you want to use any class other than those in
Math) you will need to either use the full name (packageName.ClassName) like (
java.util.ArrayList) or use one or more import statements.
Import statements have to be the first code in a Java source file. An import statement tells Java which class you mean when you use a short name (like
List). It tells Java where to find the definition of that class.
You can import just the classes you need from a package as shown below. Just provide an
import statement for each class that you want to use.
import java.util.List; // import just the List interface import java.util.ArrayList; // import just the ArrayList class
Another option is to import everything at the same level in a package using
import java.util.*; // import everything including List and ArrayList
Don’t worry about adding import statements on the AP CS A exam. Any that you need will be provided for you.