01 / 21

ArrayList
Methods

Master the essential methods for adding, removing, accessing, and modifying elements in Java's most versatile dynamic collection.

AP Computer Science A

What Is an ArrayList?

An ArrayList is a resizable array from Java's java.util package. Unlike a standard array with a fixed length, an ArrayList automatically grows and shrinks as you add or remove elements.

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();

Array vs ArrayList

Array (fixed size) "A" "B" "C" null length = 4 (cannot change) ArrayList (dynamic) "A" "B" "C" + size() grows as you add [0] [1] [2] [3] [0] [1] [2] Access: arr[i] Access: list.get(i) Stores primitives + objects Stores objects only

Why ArrayList Matters

Dynamic Size
No need to know the number of elements in advance: the list grows and shrinks automatically.
Built-in Methods
Rich API: add, remove, search, and modify elements with one method call.
AP Exam Tested
ArrayList is one of the most heavily tested topics on the AP CSA exam: both MCQ and FRQ.

The Core Methods

Method Return Type Description
add(obj) boolean Appends to end
add(index, obj) void Inserts at index, shifts right
get(index) E Returns element at index
set(index, obj) E Replaces element, returns old
remove(index) E Removes at index, shifts left
size() int Returns number of elements

add(): Appending and Inserting

list = ["Cat", "Dog", "Fox"] "Cat" "Dog" "Fox" [0] [1] [2] list.add("Owl") → appends to end "Cat" "Dog" "Fox" "Owl" [0] [1] [2] [3] list.add(1, "Bee") → inserts at index 1, shifts right "Cat" "Bee" "Dog" "Fox" "Owl"

get() and set(): Access and Modify

ArrayList<String> list = new ArrayList<String>();
list.add("Alpha");
list.add("Beta");
list.add("Gamma");

String s = list.get(1);   // returns "Beta"

String old = list.set(1, "Bravo");
// old = "Beta", list is now ["Alpha", "Bravo", "Gamma"]
get(index)
Returns the element at the given index without modifying the list. Throws IndexOutOfBoundsException if \( \text{index} < 0 \) or \( \text{index} \ge \text{size()} \).
set(index, obj)
Replaces the element at the given index and returns the old value. The list size stays the same.

remove(): Deleting Elements

Before: ["A", "B", "C", "D"] "A" "B" "C" "D" [0] [1] [2] [3] list.remove(1) → returns "B", shifts left After: ["A", "C", "D"] "A" "C" "D"

add() vs set(): The Key Distinction

Feature add(index, obj) set(index, obj)
Effect Inserts new element Replaces existing element
Size change Size increases by 1 Size stays the same
Shifting Elements shift right No shifting
Return value void The old element
Valid index 0 to size() (inclusive) \( 0 \) to \( \text{size()} - 1 \)

How to Apply ArrayList Methods

1
Declare with a type parameter. Always specify the element type: ArrayList<String>, never raw ArrayList.
2
Use add() to populate. add(obj) appends to the end. add(i, obj) inserts at position i.
3
Access with get(), modify with set(). Both require a valid index: \( 0 \) to \( \text{size()} - 1 \).
4
Remove carefully. After remove(i), all elements shift left. Adjust your loop index accordingly.
5
Use size() to control loops. Loop from \( i = 0 \) to \( i < \text{list.size()} \), not \( \le \).

Example 1: Basic Operations

ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10);          // [10]
nums.add(20);          // [10, 20]
nums.add(30);          // [10, 20, 30]
nums.add(1, 15);      // [10, 15, 20, 30]
nums.set(2, 25);      // [10, 15, 25, 30]
nums.remove(0);       // [15, 25, 30]

System.out.println(nums.get(1)); // prints 25
System.out.println(nums.size());    // prints 3

Example 2: Traversal with Loops

// Standard for loop
for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

// Enhanced for-each loop
for (String item : list) {
    System.out.println(item);
}
Standard for
Use when you need the index (for add, set, or remove inside the loop).
Enhanced for-each
Simpler syntax for read-only traversal. Cannot safely add or remove during iteration.

Example 3: Removing in a Loop

Remove all even numbers from an ArrayList<Integer>. The tricky part: indices shift after each removal.

// CORRECT: traverse backwards
for (int i = nums.size() - 1; i >= 0; i--) {
    if (nums.get(i) % 2 == 0) {
        nums.remove(i);
    }
}

// ALSO CORRECT: traverse forward, but don't increment
for (int i = 0; i < nums.size(); ) {
    if (nums.get(i) % 2 == 0)
        nums.remove(i);
    else
        i++;
}

Autoboxing and Unboxing

Java automatically converts between primitive types and their wrapper classes when working with ArrayList.

ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(42);          // autoboxing: int → Integer
int x = nums.get(0);  // unboxing: Integer → int
int 42 autoboxing Integer(42) unboxing

Common Mistakes

✕ Off-by-One in Loops
Using \( i \le \text{list.size()} \) instead of \( i < \text{list.size()} \). The last valid index is \( \text{size()} - 1 \).
✕ Forward Remove Skip
Removing in a forward loop with i++ always skips the next element. Traverse backwards or don't increment on removal.
✕ Using Primitives as Type
Writing ArrayList<int> causes a compile error. Use wrapper class Integer instead.
✕ Confusing add and set
Using set() thinking it inserts. set() replaces: size stays the same. add(index, obj) inserts.
✕ size() vs .length
Calling .length on an ArrayList (no parentheses): compile error. ArrayList uses size() method.

Summary Reference Table

Method Call Effect on List Returns Size Change
add("X") Appends "X" to end true \(+1\)
add(2, "X") Inserts "X" at index 2 void \(+1\)
get(2) No change Element at [2] 0
set(2, "X") Replaces element at [2] Old element 0
remove(2) Removes at [2], shifts left Removed element \(-1\)
size() No change int count 0

Question 1 of 5

What is the output of the following code?

ArrayList<String> a = new ArrayList<String>();
a.add("P");
a.add("Q");
a.add("R");
a.add(1, "S");
System.out.println(a);

Question 2 of 5

What does set() return?

Question 3 of 5

Consider:

ArrayList<Integer> n = new ArrayList<Integer>();
n.add(5); n.add(10); n.add(15); n.add(20);
n.remove(1);
System.out.println(n.get(2));

What is the output?

Question 4 of 5

Which loop correctly removes all occurrences of "X" from an ArrayList<String> called list?

Question 5 of 5

What is the difference between add(2, "Z") and set(2, "Z") when called on an ArrayList of size 5?