AP Computer Science A
One-page, printable cheatsheet
Cheatsheet visualization
Table of Contents

💻ap computer science a review

7.1 Introduction to ArrayList

Verified for the 2025 AP Computer Science A examCitation:

Arrays are powerful, but they have limitations—particularly their fixed size. The ArrayList class gives us a more flexible alternative that can grow or shrink as needed. In this guide, we'll explore how ArrayList works and why it's such a useful tool for managing collections of objects.

What is an ArrayList?

An ArrayList is a built-in Java class that stores a list of objects. Unlike regular arrays, an ArrayList:

  • Can dynamically resize itself (grow or shrink)
  • Provides many helpful built-in methods
  • Stores only object references, not primitive values
  • Is part of the Java Collections Framework

Think of an ArrayList like a smarter, more flexible array that can adjust its capacity as you add or remove elements.

Key Properties of ArrayList

1. ArrayList is Mutable

Unlike regular arrays, ArrayList objects are mutable, which means you can:

  • Add new elements at any time
  • Remove elements when needed
  • Change existing elements
  • Reorder elements
ArrayList<String> names = new ArrayList<String>();
names.add("Alice");       // Add an element
names.remove(0);          // Remove an element
names.add("Bob");         
names.set(0, "Charlie");  // Change an element

2. ArrayList Stores Object References

ArrayList can only store references to objects, not primitive types like int, double, or boolean. For example:

// This works - String is an object type

ArrayList<String> words = new ArrayList<String>();

// This won't work - int is a primitive type

// ArrayList<int> numbers = new ArrayList<int>(); // ERROR!

To store primitive values, you must use wrapper classes:

Primitive TypeWrapper Class
intInteger
doubleDouble
booleanBoolean
charCharacter
// This works - using the Integer wrapper class

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(42);  // Java automatically converts (autoboxes) int to Integer

Creating an ArrayList

Basic Constructor

To create an empty ArrayList, use the constructor:

// Creates an empty ArrayList that will store String objects
ArrayList<String> names = new ArrayList<String>();

The part between the angle brackets <> is the generic type parameter, which specifies what type of objects this ArrayList will store.

Importing ArrayList

Before using ArrayList, you need to import it from the Java utility package:

import java.util.ArrayList;

Add this line at the top of your file, before your class definition.

Using Generics with ArrayList

What Are Generics?

Generics allow you to specify what type of objects an ArrayList can contain. The syntax uses angle brackets <> with a type parameter:

ArrayList<E>

Where E is a placeholder for the actual type you want to store.

Specifying the Element Type

When you create an ArrayList, replace E with the actual type:

// An ArrayList that stores Strings
ArrayList<String> cities = new ArrayList<String>();

// An ArrayList that stores Integer objects
ArrayList<Integer> scores = new ArrayList<Integer>();

// An ArrayList that stores Student objects
ArrayList<Student> students = new ArrayList<Student>();

Benefits of Using Generics

Using generics with ArrayList<E> is preferred over the raw type ArrayList because:

  1. Compile-time type checking: The compiler can catch type errors before your program runs
  2. No need for casting: You know exactly what type of objects are stored
  3. Better code readability: Makes your intentions clear
  4. Prevents runtime errors: Helps avoid ClassCastException errors that might occur with raw types
// With generics - type safe, no casting needed

ArrayList<String> names = new ArrayList<String>();
names.add("Alex");
String name = names.get(0);  // No casting needed

// Without generics (not recommended)
ArrayList rawList = new ArrayList();
rawList.add("Alex");
String str = (String) rawList.get(0);  // Casting required and might fail

Example: Using ArrayList

Here's a complete example showing the basics of ArrayList:

import java.util.ArrayList;

public class StudentRoster {
    public static void main(String[] args) {
        // Create an ArrayList to store student names
        ArrayList<String> students = new ArrayList<String>();
        
        // Add students
        students.add("Maria");
        students.add("Juan");
        students.add("Lee");
        
        // Print the list size
        System.out.println("Number of students: " + students.size());
        
        // Access elements
        System.out.println("First student: " + students.get(0));
        
        // Modify an element
        students.set(1, "John");
        
        // Print all students
        System.out.println("Updated student list:");
        for (String student : students) {
            System.out.println("- " + student);
        }
        
        // Remove a student
        students.remove(2);
        
        // Check if list contains a student
        if (students.contains("Maria")) {
            System.out.println("Maria is in the class.");
        }
        
        // Clear the list
        students.clear();
        System.out.println("Students after clearing: " + students.size());
    }
}

ArrayList vs Array: Key Differences

FeatureArrayListArray
SizeDynamic (can grow/shrink)Fixed (cannot change after creation)
Type of elementsObjects only (uses wrapper classes for primitives)Any type (primitives or objects)
MethodsMany built-in methods (add, remove, etc.)No built-in methods
Memory usageMore overhead (but more convenient)More efficient (but less flexible)
SyntaxArrayList<Type> name = new ArrayList<Type>();Type[] name = new Type[size];
AccessMethods: get(index), set(index, value)Direct: array[index], array[index] = value

When to Use ArrayList

ArrayList is best when:

  • You don't know exactly how many elements you'll need
  • You need to frequently add or remove elements
  • You want convenient built-in methods
  • You're working with objects, not primitives
  • You want clearer error messages for index problems

Arrays are better when:

  • You know the exact size needed
  • You need maximum performance
  • You're working with primitive types
  • You need a multi-dimensional collection

Summary

The ArrayList class offers a flexible, resizable alternative to fixed-size arrays. It stores object references (not primitives) and provides many helpful methods for adding, removing, and manipulating elements. Using generics (ArrayList<E>) ensures type safety and helps prevent errors. While arrays are still useful in certain scenarios, ArrayList is often the better choice when you need a dynamic collection of objects that can grow or shrink as your program runs.

Key Terms to Review (11)

ArrayLists: ArrayLists are dynamic arrays that can grow and shrink dynamically as needed. They provide resizable arrays with additional methods for easy manipulation and management.
Autoboxing: Autoboxing is the automatic conversion of a primitive data type to its corresponding wrapper class object. For example, when an int is assigned to an Integer object, autoboxing occurs.
Constructor: A constructor is a special method within a class that is used to initialize objects of that class. It is called automatically when an object is created and helps set initial values for its attributes.
Deques: Deques, short for double-ended queues, are data structures that allow insertion and removal of elements from both ends. They can be used to implement stacks and queues efficiently.
Generics: Generics in Java allow you to create classes and methods that can work with different types (e.g., integers, strings) without sacrificing type safety. They provide flexibility and reusability in your code.
Import Statement: An import statement in Java is used to bring classes or packages from other libraries into your current program. It allows you to use those classes or packages without having to fully qualify their names.
LinkedLists: LinkedLists are linear data structures where each element, called a node, contains a reference to the next node in the sequence. They provide efficient insertion and deletion operations but have slower access times compared to arrays.
Maps: Maps, also known as dictionaries or associative arrays, are data structures that store key-value pairs. They allow efficient retrieval of values based on their corresponding keys.
Unboxing: Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive data type. For example, when an Integer object is assigned to an int variable, unboxing occurs.
Type Checking: Type checking refers to the process of verifying whether the usage of types in a program is consistent with their definitions. It helps catch errors at compile-time by ensuring that operations are performed on compatible types.
Wrapper Classes: Wrapper classes are classes in Java that provide a way to wrap primitive data types into objects. They allow us to perform operations on primitives as if they were objects.