7.1. Intro to ArrayLists

../_images/lists.jpg

Figure 1: A couple of lists

In the last unit, we learned about arrays to hold collections of related data. But arrays have limitations. The size of an array is established at the time of creation and cannot be changed. What if you don’t know how big the collection of data will be? What if you want to add and remove items from the collection and change the size of the collection while the program is running? For example, if you wanted to represent a shopping list, you might add to the list throughout the week and remove things from the list while you are shopping. You probably would not know how many items will be on the list at the beginning of the week.

Luckily, Java has a class called ArrayList which is a re-sizable array. An ArrayList has an underlying array that grows or shrinks as needed. You can use ArrayList instead of arrays whenever you don’t know the size of the array you need or you know that you will add and remove items changing the array’s size dynamically during run time. An ArrayList is mutable, meaning it can change during runtime by adding and removing objects from it.

An ArrayList is often called just a list on the CS A exam. In past AP CS A exams, the interface List is often used to declare an ArrayList. Interfaces are no longer on the exam, but if you see List being used, just assume it’s an ArrayList.

    7-1-1: Which of the following is a reason to use an ArrayList instead of an array?

  • A list will always use less memory than an array.
  • No, an ArrayList grows as needed so it will typically be bigger than the data you put it in. If you try to add more data and the array is full, it usually doubles in size.
  • A list can store objects, but arrays can only store primitive types.
  • No, you can have an array of objects.
  • A list has faster access to the last element than an array.
  • No, an ArrayList is implemented using an array so it has the same access time to any index as an array does.
  • A list resizes itself as necessary as items are added, but an array does not.
  • An ArrayList is really a dynamic array (one that can grow or shrink as needed).

7.1.1. Import Package

The ArrayList class is in the java.util package. A package is a set or library of related classes. The java.lang package is the main Java language classes that you get automatically without importing it. The java.util package has a lot of utility classes that you can use if you import the package. If you want to use any class other than those in java.lang you will need to either use the full name (packageName.ClassName) like (java.util.ArrayList) or use one or more import statements to import in that package.

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 ArrayList). 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.ArrayList; // import just the ArrayList class

Another option is to import everything at the same level in a package using import packageName.*.

import java.util.*; // import everything in package including ArrayList

Note

Don’t worry about adding import statements on the AP CS A exam. Any that you need will be provided for you.

exercise Check your understanding

    7-1-2: Which of the following is true about import statements?

  • You can only have one import statement in a source file.
  • You can have an many import statements as you need.
  • You must specify the class to import.
  • You can use * to import all classes at the specified level.
  • Import statements must be before other code in a Java source file.
  • Import statements have to be the first Java statements in a source file.
  • You must import java.lang.String to use the short name of String.
  • You do not have to import any classes that are in the java.lang package.

7.1.2. Declaring and Creating ArrayLists

To declare a ArrayList use ArrayList<Type> name Change the Type to be whatever type of objects you want to store in the ArrayList like String to hold strings as shown in the code below. You don’t have to specify the generic type <Type>, since it will default to Object, but it is good practice to specify it to restrict what you allow in your ArrayList. The generic type ArrayList<Type> is preferred over ArrayList because it allows the compiler to find errors that would otherwise be found at run-time.

// ArrayList<Type> name = new ArrayList<Type>();
// An ArrayList of Strings:
ArrayList<String> shoppingList = new ArrayList<String>();

coding exercise Coding Exercise

In the code below we are declaring a variable called nameList that can refer to a ArrayList of strings, but currently doesn’t refer to any ArrayList yet (it’s set to null). Can you guess what it will print out when you run it?

Declaring a ArrayList doesn’t actually create a ArrayList. It only creates a variable that can refer to a ArrayList. To actually create a ArrayList use new ArrayList<Type>(). If you leave off the <Type> it will default to Object.

You can get the number of items in a ArrayList using the size() method. Notice that an empty ArrayList has a size of 0 because the ArrayList constructor constructs an empty list. Also notice that you can’t get the size of a ArrayList that is currently set to null on line 9. You will get a NullPointerException instead, which means that you tried to do something with an object reference that was null (doesn’t exist).

You can also create ArrayLists of integer values. However, you have to use Integer as the type because ArrayLists can only hold objects, not primitive values. All primitive types must be wrapped in objects before they are added to an ArrayList. For example, int values can be wrapped in Integer objects, double values can be wrapped in Double objects. You can actually put in any kind of Objects in an ArrayList, even for a class that you wrote in Unit 5 like Student or Person or Pet.

Here’s an example of a Integer ArrayList:

exercise Check your understanding

    7-1-3: Which of the following is the correct way to create an ArrayList of integers?

  • ArrayList[int] numbers = new ArrayList();
  • The square brackets [] are only used with arrays, not ArrayLists.
  • ArrayList<Integer> numbers = new ArrayList();
  • Although the left side of the declaration is right, you must also specify the type on the right side when creating the ArrayList.
  • ArrayList<int> numbers = new ArrayList<int>();
  • ArrayLists cannot hold primitive types like int. You must use the wrapper class Integer.
  • ArrayList<Integer> numbers = new ArrayList<Integer>();
  • The wrapper class Integer is used to hold integers in an ArrayList.

Although it is not on the AP exam, you can convert arrays to ArrayLists using its constructor with an argument Arrays.asList(arrayname) like the following. Note that ArrayLists have a toString() method that is automatically called to print the list in a nice format.

coding exercise Coding Exercise

You can add values to an ArrayList by using its add method, described in detail in the next lesson. Try the code below. Can you add another item to the shopping list? Note that the type of the ArrayList, String or Integer, also determines the type of parameters and return types for all of its methods, so add and print work for any type of ArrayList.

7.1.3. groupwork Programming Challenge : FRQ Digits

This programming challenge is based on the 2017 Free Response Question part 1a on the 2017 AP CS A exam. In this question, you are asked to write a constructor for a class called Digits. This constructor takes an integer number as its argument and divides it up into its digits and puts the digits into an ArrayList. For example, new Digits(154) creates an ArrayList with the digits [1, 5, 4].

First, let’s discuss how to break up a number into its digits. Try the code below. What happens if you divide an integer by 10? Remember that in integer division the result truncates (cuts off) everything to the right of the decimal point. Which digit can you get by using mod 10 which returns the remainder after dividing by 10? Try a different number and guess what it will print and then run to check.

Change the code above to use a while loop to print out each digit in reverse order starting from the right (4, 5, 1 for the number 154) while dividing it by 10. Here is the pseudocode:

  • while number is greater than 0

    • print out the last digit using %

    • change the number to cut off the last digit using /

Now, let’s write a constructor for the Digits class that uses this loop and adds each found digit to the ArrayList instead of printing it out. You can use a special method called Collections.reverse(digitsList); to reverse the order of the digits in the ArrayList after the loop to get them in the right order. In the next lesson, we will also learn how to use a different add method that adds in elements at any index instead of the end.

7.1.4. Summary

  • ArrayList are re-sizable arrays that allow adding and removing items to change their size during run time.

  • The ArrayList class is in the java.util package. You must import java.util.* to use it.

  • An ArrayList object contains object references and is mutable, meaning it can change (by adding and removing items from it).

  • The ArrayList constructor ArrayList() constructs an empty list of size 0.

  • Java allows the generic type ArrayList<E>, where the generic type E specifies the type of the elements, like String or Integer. Without it, the type will be Object.

  • ArrayList<E> is preferred over ArrayList because it allows the compiler to find errors that would otherwise be found at run-time.

  • When ArrayList<E> is specified, the types of the reference parameters and return type when using its methods are type E.

  • ArrayLists cannot hold primitive types like int or double, so you must use the wrapper classes Integer or Double to put numerical values into an ArrayList.

You have attempted of activities on this page
Next Section - 7.2. ArrayList Methods