Topic 4.9 — ArrayList Methods

Goal: know the core ArrayList methods you’ll use on AP CSA, what they return, and how they affect indexes and list size.

The big idea

You don’t access an ArrayList with brackets. You use methods. Most AP questions are testing whether you understand what each method does and how insert/remove shifts elements.

If you can predict how the list changes after a method call, you’re set.

Core methods (AP must-know)

MethodWhat it doesReturn value
size() number of elements int
get(i) reads element at index i Type
set(i, x) replaces element at i with x the old element
add(x) adds x to end boolean (often ignored)
add(i, x) inserts at i (shifts right) void
remove(i) removes element at i (shifts left) the removed element

add: append vs insert

ArrayList<String> list = new ArrayList<>();
list.add("A");      // ["A"]
list.add("C");      // ["A", "C"]

list.add(1, "B");   // insert at index 1
// ["A", "B", "C"]

Insert shifts everything at and after index 1 to the right.

get vs set

ArrayList<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);

// get reads
int x = nums.get(1);      // 20

// set replaces and returns old value
int old = nums.set(1, 99); // old = 20, nums is [10, 99]

set does NOT change size

It replaces an existing element—no shifting, no growth.

// size stays the same
nums.set(0, 123);

remove shifts left

After you remove index i, everything after it moves left.

ArrayList<String> a = new ArrayList<>();
a.add("A");
a.add("B");
a.add("C");

String removed = a.remove(1); // removes "B"
 // removed = "B"
 // a is ["A", "C"]

Removing in a loop: safe patterns

If you remove by index, looping backward avoids skipping.

for (int i = list.size() - 1; i >= 0; i--) {
  if (list.get(i).equals("X")) {
    list.remove(i);
  }
}

Index bounds to remember

  • First valid index: 0
  • Last valid index: list.size() - 1
  • For add(i, x), you can insert at i == list.size() (that’s “add to end”).
// Equivalent:
list.add(x);
list.add(list.size(), x);

Quick self-check

  1. What does set(i, x) return?
  2. Does set change list size?
  3. After remove(i), what happens to the element that was at i+1?
  4. What’s the difference between add(x) and add(i, x)?
  5. Why can removing while looping forward skip elements?

← Back to Unit 4 topics