Skip to main content

Section 9.10 From the Java Library: java.util.ArrayList

The java.util.ArrayList class (https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html) implements an array of objects that can grow in size as needed. One limitation of regular arrays is that their lengths remain fixed. Once the array is full — once every element is used — you can't allocate additional elements.

The ArrayList class contains the methods listed in Figure 9.10.1 for storing and retrieving objects, and for accessing objects by their index position within the ArrayList.

Figure 9.10.1. Public methods in the ArrayList class.

One use for a ArrayList would be when a program needs to store input from the user or a file without knowing in advance how many items there are. Using a ArrayList is less efficient than an array in terms of processing speed, but it gives you the flexibility of growing the data structure to meet the storage requirements.

As an illustration of this idea, the program in Listing 9.10.2 creates a random number of integers and then stores them in a ArrayList. The ArrayList, which is declared and instantiated in main(), is initially empty. Integers from 0 to the random bound are then inserted into the ArrayList. In this case, insertions are done with the add() method, which causes the ArrayList object to insert the element at the next available location, increasing its size, if necessary. Once all the integers have been inserted, the printArrayList() method is called. Note that it uses the size() method to determine how many elements the ArrayList contains, and the get() method to get elements out of the ArrayList similar to [] in arrays. Run the program below multiple times to see ArrayLists of different sizes.

Listing 9.10.2. Demonstration of the ArrayList class.

ArrayLists can only hold Objects, for example String, the wrapper classes Integer and Double, or even a new programmer defined class like Student. They cannot hold primitive types like int, double, etc. To declare an ArrayList, we use a generic Object type like Integer, Double, String, Object. If you don't specify the type, it will default to Object. In the program above, when a number is added to the ArrayList, it will automatically be wrapped into an Integer object.

// ArrayList<Type> 
ArrayList<Integer> numList = new ArrayList<Integer>(); 
ArrayList<String> nameList = new ArrayList<String>(); 
ArrayList<Double> decList = new ArrayList<Double>(); 
ArrayList objects = new ArrayList(); // a list of Objects

By defining ArrayList to store objects, Java's designers have made it as general as possible and, therefore, as widely useful as possible.

You have attempted of activities on this page.