| Study Guides
AP · ArrayList · 16 min read · Updated 2026-05-07

ArrayList — AP Computer Science A CS A Study Guide

For: AP Computer Science A candidates sitting AP Computer Science A.

Covers: Creating and using ArrayList, key differences between ArrayList and standard arrays, core ArrayList methods, for-each loop traversal, and common ArrayList algorithms tested on the AP CS A exam.

You should already know: Basic Java or any other procedural-language programming.

A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers and may differ in wording, numerical values, or context. Use them to practise the technique; cross-check with official College Board mark schemes for grading conventions.


1. What Is ArrayList?

ArrayList is Java’s resizable array implementation, part of the java.util Collections framework, designed to store ordered collections of object references where the total number of elements may change during runtime. Unlike standard fixed-size arrays, ArrayList automatically adjusts its internal capacity as you add or remove elements, eliminating the need for manual memory reallocation. It is the focus of Unit 7 in the AP CS A Course and Exam Description, accounting for 7-10% of your total exam score, and appears in at least one free-response question (FRQ) on every AP CS A exam.

2. Creating and using ArrayList

Before using ArrayList, you must first import it at the top of your Java file: import java.util.ArrayList; — this is a mandatory step, and missing it will cause compilation errors that cost marks on the exam.

Declaration and Initialization Syntax

ArrayList uses generic type parameters to define the type of elements it stores, which must be a reference type (not a primitive like int or double). For primitives, use the corresponding wrapper class: Integer for int, Double for double, Character for char, and Boolean for boolean.

// Standard declaration (Java 7+ diamond operator is accepted on AP CS A)
ArrayList<ElementType> listName = new ArrayList<>();

// Optional: Set initial capacity (pre-allocates memory, does not set size)
ArrayList<String> studentNames = new ArrayList<>(20);

The initial capacity parameter is optional; if omitted, ArrayList defaults to an initial capacity of 10. Note that capacity is not the same as size: a new ArrayList always has a size of 0 until you add elements.

Worked Example

import java.util.ArrayList;

public class GradeTracker {
 public static void main(String[] args) {
 // Create ArrayList to store test scores (uses Integer wrapper for int primitives)
 ArrayList<Integer> testScores = new ArrayList<>();
 
 // Add elements to the list (auto-boxing converts int to Integer automatically)
 testScores.add(85);
 testScores.add(92);
 testScores.add(78);
 testScores.add(90);
 
 System.out.println(testScores); // Output: [85, 92, 78, 90]
 }
}

Auto-boxing (automatic conversion of primitives to wrapper classes) and unboxing (automatic conversion of wrapper classes to primitives) are allowed and expected on the AP CS A exam, so you do not need to manually wrap/unwrap values for ArrayList use.

3. ArrayList vs array

The difference between ArrayList and standard arrays is one of the most frequently tested multiple-choice topics on the exam. The table below summarizes key distinctions:

Feature Standard Array ArrayList
Size Fixed at declaration, cannot be changed after creation Dynamically resizes automatically as elements are added/removed
Supported types Stores both primitives and reference types Only stores reference types; requires wrapper classes for primitives
Length access Uses public length field (e.g., arr.length) Uses size() method (e.g., list.size())
Element access/modification Uses square bracket notation: arr[index] = value Uses methods: list.get(index) and list.set(index, value)
Built-in operations No built-in add/remove methods; requires manual array copying for size changes Has built-in methods for adding, removing, searching, and sorting elements

Worked Comparison: Adding a 4th Element

For a standard array of 3 names, adding a 4th requires creating a new larger array and copying all existing elements:

String[] namesArr = new String[3];
namesArr[0] = "Alice";
namesArr[1] = "Bob";
namesArr[2] = "Charlie";

// Add 4th name
String[] newNamesArr = new String[4];
for (int i=0; i<namesArr.length; i++) {
 newNamesArr[i] = namesArr[i];
}
newNamesArr[3] = "Diana";
namesArr = newNamesArr;

For ArrayList, the same operation takes one line:

ArrayList<String> namesList = new ArrayList<>();
namesList.add("Alice");
namesList.add("Bob");
namesList.add("Charlie");
namesList.add("Diana"); // No manual resizing needed

Exam tip: Examiners will ask you to choose between array and ArrayList for a given scenario: use an array if the size is fixed and known upfront, use ArrayList if elements will be added or removed during runtime.

4. Common methods — add, remove, get, set, size

The AP CS A exam explicitly tests 5 core ArrayList methods, which you must memorize perfectly. All methods throw an IndexOutOfBoundsException if you pass an index that is negative or greater than/equal to the list size (except where noted below):

  1. int size(): Returns the number of elements in the list. An empty list returns 0.
  2. E get(int index): Returns the element stored at the specified index (0-indexed, like arrays).
  3. E set(int index, E newValue): Replaces the element at the specified index with newValue, and returns the old value that was replaced.
  4. boolean add(E value): Appends value to the end of the list, increases size by 1, and always returns true (you do not need to use the return value on the exam).
  • Overload: void add(int index, E value): Inserts value at the specified index, shifting all elements after the index one position to the right. You may insert at index equal to size() (this is equivalent to appending to the end of the list).
  1. E remove(int index): Removes the element at the specified index, shifts all elements after the index one position to the left, decreases size by 1, and returns the removed element.
  • Overload: boolean remove(E value): Removes the first occurrence of value from the list, returns true if the value was found and removed.

Worked Example

ArrayList<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie", "Diana"));
System.out.println(names.size()); // Output: 4
System.out.println(names.get(1)); // Output: Bob
System.out.println(names.set(2, "Charlotte")); // Output: Charlie (old value)
names.add(1, "Bella"); // Insert at index 1
System.out.println(names); // Output: [Alice, Bella, Bob, Charlotte, Diana]
System.out.println(names.remove(3)); // Output: Charlotte
System.out.println(names.remove("Bob")); // Output: true
System.out.println(names); // Output: [Alice, Bella, Diana]

5. Traversal with for-each loop

The for-each (enhanced for) loop is the simplest way to traverse an ArrayList when you do not need to modify the list or access the index of each element.

Syntax

for (ElementType elementVariable : listName) {
 // Code to run for each element
}

Advantages

  • No index variable to manage, eliminating the risk of off-by-one errors
  • Cleaner, more readable code for simple traversals
  • Automatic unboxing of wrapper types to primitives

Limitations (Exam Critical)

  • You cannot add or remove elements from the list during traversal: this will throw a ConcurrentModificationException
  • You cannot access the index of the current element
  • You can only traverse forward from the first to last element, no reverse traversal

Worked Example: Calculate Average Score

ArrayList<Integer> scores = new ArrayList<>(List.of(85, 92, 78, 90, 88));
int sum = 0;
for (int score : scores) { // Unboxes Integer to int automatically
 sum += score;
}
double average = sum / (double) scores.size();
System.out.println(average); // Output: 86.6

Exam tip: For-each loops are awarded full marks for all valid use cases on the exam, but you must use a standard indexed for loop if you need to modify the list (e.g., remove elements) or access element indices.

6. Algorithms — sum, max, search, etc.

The following ArrayList algorithms are tested repeatedly on both multiple choice and FRQ sections of the AP CS A exam. You should be able to write each from memory in 2 minutes or less:

1. Sum / Average

We covered sum above; for average, always cast the sum to double before dividing by size to avoid integer division, and add a check for empty lists to avoid division by zero:

public static double getAverage(ArrayList<Integer> list) {
 if (list.size() == 0) return 0.0;
 int sum = 0;
 for (int num : list) sum += num;
 return sum / (double) list.size();
}

2. Find Maximum / Minimum Value

Initialize the max/min variable to the first element of the list, then iterate through all remaining elements, updating the variable if you find a larger/smaller value:

public static int findMax(ArrayList<Integer> list) {
 if (list.size() == 0) return -1; // Sentinel value for empty list
 int max = list.get(0);
 for (int num : list) {
 if (num > max) max = num;
 }
 return max;
}

3. Linear Search

Search for a target value and return its index if found, return -1 if not found. Always use .equals() for comparing reference types like String, never ==:

public static int linearSearch(ArrayList<String> list, String target) {
 for (int i=0; i<list.size(); i++) {
 if (list.get(i).equals(target)) {
 return i;
 }
 }
 return -1;
}

4. Filter Elements

Create a new list containing only elements that meet a specified condition (e.g., all scores above 80):

public static ArrayList<Integer> getHighScores(ArrayList<Integer> scores) {
 ArrayList<Integer> highScores = new ArrayList<>();
 for (int s : scores) {
 if (s >= 80) highScores.add(s);
 }
 return highScores;
}

7. Common Pitfalls (and how to avoid them)

These are the most frequent mistakes that cost marks on ArrayList exam questions:

  1. Forgetting to import java.util.ArrayList: Students often skip imports when writing code quickly under time pressure, leading to compilation errors. Correct move: Always write the import statement first whenever you are asked to use ArrayList on an FRQ.
  2. Using primitive types as the ArrayList type parameter: Students confuse arrays (which support primitives) with ArrayList, leading to code like ArrayList<int> scores = new ArrayList<>(). Correct move: Use wrapper classes for primitives: Integer for int, Double for double, etc.
  3. Off-by-one index errors: Students use i <= list.size() instead of i < list.size() for indexed loops, leading to IndexOutOfBoundsException. Correct move: The last valid index of an ArrayList is always list.size() - 1, so loop from i=0 to i < list.size().
  4. Accidentally removing by index instead of value for Integer lists: The remove method has two overloads, and an int parameter will always match the index overload first. If you write nums.remove(3) for an ArrayList<Integer>, it will remove the element at index 3, not the element with value 3. Correct move: Cast the value to Integer to use the value removal overload: nums.remove(Integer.valueOf(3)).
  5. Modifying the list during for-each traversal: Adding or removing elements while using a for-each loop throws a ConcurrentModificationException. Correct move: Use an indexed for loop traversing from the end of the list to the start when removing elements, to avoid skipping elements after removal.

8. Practice Questions (AP Computer Science A Style)

Question 1 (Multiple Choice)

Which of the following code segments correctly creates an ArrayList of decimal values and adds the values 1.5, 2.5, and 3.5? A) ArrayList<double> nums = new ArrayList<>(); nums.add(1.5); nums.add(2.5); nums.add(3.5); B) ArrayList<Double> nums = new ArrayList<>(); nums.add(1.5); nums.add(2.5); nums.add(3.5); C) double[] nums = new ArrayList<Double>(); nums.add(1.5); nums.add(2.5); nums.add(3.5); D) ArrayList<Double> nums = new ArrayList[3]; nums[0] = 1.5; nums[1] = 2.5; nums[2] = 3.5;

Solution: Correct answer is B. Explanation: A is invalid because double is a primitive and cannot be used as an ArrayList type parameter. C is invalid because nums is declared as an array type, not an ArrayList. D is invalid because ArrayList elements are added/accessed with add() and get(), not square bracket notation.

Question 2 (FRQ Style)

Write a method countEven that takes an ArrayList<Integer> as a parameter and returns the number of even integers in the list. If the list is empty, return 0.

Solution:

public static int countEven(ArrayList<Integer> list) {
 int count = 0;
 for (int num : list) {
 if (num % 2 == 0) {
 count++;
 }
 }
 return count;
}

Explanation: The method uses a for-each loop to traverse the list, checks if each number is even using modulo 2, and increments the count for each even number. For empty lists, the loop does not run and returns 0 as required.

Question 3 (FRQ Style)

Write a method removeLongStrings that takes an ArrayList<String> and an integer maxLength as parameters. The method removes all strings from the list that have a length greater than maxLength.

Solution:

public static void removeLongStrings(ArrayList<String> list, int maxLength) {
 for (int i = list.size() - 1; i >= 0; i--) {
 if (list.get(i).length() > maxLength) {
 list.remove(i);
 }
 }
}

Explanation: Traversing from the end of the list to the start avoids skipping elements after removal: when you remove an element at index i, only elements with indices less than i (already checked) shift position, so no elements are skipped. If you traversed from start to end, removing an element at index i would shift the element at i+1 to index i, and the loop would skip checking that element.

9. Quick Reference Cheatsheet

Operation Syntax Key Notes
Import import java.util.ArrayList; Mandatory for all ArrayList use
Declare ArrayList<E> list = new ArrayList<>(); E must be a reference type (e.g., String, Integer)
Get size int n = list.size(); Returns number of elements in the list
Access element E val = list.get(index); Valid index range: 0 <= index < list.size()
Replace element E oldVal = list.set(index, newVal); Returns the original value at the index
Add to end list.add(val); Increases list size by 1
Insert at index list.add(index, val); Shifts elements after index to the right
Remove by index E removed = list.remove(index); Shifts elements after index to the left
Remove by value boolean found = list.remove(val); Removes first occurrence of val
For-each traversal for (E elem : list) { ... } Do not add/remove elements during traversal
Sum of integers int sum = 0; for (int n : list) sum +=n; Cast to double for average calculation
Find max int max = list.get(0); for (int n : list) if (n>max) max =n; Check list is not empty before use
Linear search for (int i=0; i<list.size();i++) if (list.get(i).equals(target)) return i; return -1; Use .equals() for object comparison, not ==

10. What's Next

ArrayList is a foundational data structure that connects directly to later topics in the AP CS A syllabus. You will use ArrayLists to store instances of custom classes you write in Unit 5 (Classes and Objects), manipulate lists of data in Unit 8 (2D Arrays), and even traverse them recursively in Unit 10 (Recursion). It is also the most frequently tested data structure on the FRQ section, with at least one FRQ per exam requiring ArrayList manipulation, so mastering this topic directly improves your score potential for 25% of the total exam marks.

If you have any questions about ArrayList syntax, methods, or exam-style problems, you can ask Ollie for personalized explanations, additional practice problems, or step-by-step walkthroughs of past exam questions any time on the homepage. Once you are comfortable with ArrayLists, you can move on to our next study guide for 2D Arrays, the next core data structure in the AP CS A curriculum.

← Back to topic

Stuck on a specific question?
Snap a photo or paste your problem — Ollie (our AI tutor) walks through it step-by-step with diagrams.
Try Ollie free →