---
title: "ArrayList Methods | FiveStudy"
description: "All six exam methods on one table, the add/remove index shift traced step by step, and the four traps that cost the most points."
url: https://fivestudy.com/guides/arraylist-methods
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# ArrayList Methods

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Data Collections

AP® Computer Science A · Data Collections

# *ArrayList* Methods

A list that grows and shrinks: creating an ArrayList with a type parameter, and the methods size, add, get, set, and remove, including how inserting and removing shift the other elements.

1. What an ArrayList Is 2. Creating a List 3. Adding Elements 4. Reading and Replacing 5. Removing Elements 6. Indices and Types

Big Picture

An **`ArrayList`** object is mutable in size and contains object references. Unlike an array, its size changes as elements are added and removed. The constructor `ArrayList()` constructs an empty list, and the generic type `ArrayList<E>` names the element type so the compiler can catch mistakes. The class is in `java.util` and must be imported. Its methods `size`, `add`, `get`, `set`, and `remove` read and change the list; indices run from 0 to the number of elements minus 1.

## 1 What an ArrayList Is

Arrays have a fixed length, which is awkward when the amount of data is not known in advance or changes while the program runs. An `ArrayList` object is mutable in size: adding an element makes it one longer, and removing one makes it one shorter. Like an array, it keeps its elements in order, and each has an index starting at 0.

An `ArrayList` contains object references, never primitives. A list of words is an `ArrayList<String>`; a list of whole numbers is an `ArrayList<Integer>`, with autoboxing converting `int` values as they are added and unboxing converting them back when they are read into `int` variables.

**Figure 1.** An `ArrayList` object is mutable in size and contains object references, unlike an array, whose length is fixed when it is created.

|  | Array | ArrayList |
| --- | --- | --- |
| Size | Fixed at creation: `a.length` | Changes: `list.size()` |
| Element types | Primitives or references | References only (use Integer, Double for numbers) |
| Read | `a[i]` | `list.get(i)` |
| Write | `a[i] = v;` | `list.set(i, v);` |
| Bad index | ArrayIndexOutOfBoundsException | IndexOutOfBoundsException |
| Import needed | No | Yes: `java.util.ArrayList` |

## 2 Creating a List

The `ArrayList` class is part of the `java.util` package, so an `import` statement must be used to make it available: `import java.util.ArrayList;`. The constructor `ArrayList()` constructs an empty list, whose size is 0.

Java allows the generic type `ArrayList<E>`, where the type parameter `E` specifies the type of the elements. When `ArrayList<E>` is specified, the types of the reference parameters and return type when using the methods are type `E`. `ArrayList<E>` is preferred over plain `ArrayList`; for example, `ArrayList<String> names = new ArrayList<String>();` allows the compiler to find errors that would otherwise be found at run time.

Worked Example 1 Creating and adding

### Building a List

Predict the output.

Code

```
ArrayList<String> trees = new ArrayList<String>();
System.out.println(trees.size());
trees.add("pine");
trees.add("oak");
trees.add("elm");
System.out.println(trees.size());
System.out.println(trees.get(0) + " " + trees.get(2));
System.out.println(trees);
```

Output

```
0
3
pine elm
[pine, oak, elm]
```

1. 1 **`new ArrayList<String>()`** constructs an empty list of strings: size 0.
2. 2 **`add(obj)`** appends to the end each time; after three calls the size is 3.
3. 3 **`get(index)`** reads by index, starting at 0.
4. 4 **Printing the list** shows its elements in brackets.

**Result:** The output is 0, 3, pine elm, and [pine, oak, elm]. An `ArrayList` starts empty and grows as elements are added.

Worked Example 2 Generic types

### The Compiler Checks the Element Type

Explain the compile error.

Code that does not compile

```
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add(42);
```

1. 1 **`ArrayList<String>`** declares that every element is a `String`.
2. 2 **`add(42)`** tries to add an `int`, which cannot become a `String`, so the compiler rejects it.
3. 3 **This is the benefit of the type parameter:** the mistake is caught when compiling instead of causing a failure while the program runs.

**Result:** The code does not compile. Specifying `ArrayList<E>` lets the compiler find errors that would otherwise be found at run time.

## 3 Adding Elements

There are two `add` methods. `boolean add(E obj)` appends `obj` to the end of the list and returns `true`. `void add(int index, E obj)` inserts `obj` at position `index`, where 0 ≤ `index` ≤ `size()`, moving the elements at position `index` and higher to the right, adding 1 to their indices, and adding 1 to the size.

Inserting at index 0 puts the new element first; inserting at an index equal to the current size appends it, exactly like the one-argument `add`. Any index greater than the size, or negative, throws an `IndexOutOfBoundsException`.

Appending is the most common way to build a list, for example while reading values from a file, because the program does not need to know in advance how many values there will be. Inserting at a specific position is useful for keeping a list in order as new elements arrive.

**Figure 2.** `add(int index, E obj)` inserts at `index`, moving elements at that position and higher to the right and adding 1 to the size.

| Method | What it does | Returns |
| --- | --- | --- |
| `ArrayList()` | Constructs an empty list | — |
| `int size()` | Number of elements | The size |
| `boolean add(E obj)` | Appends obj to the end | true |
| `void add(int index, E obj)` | Inserts at index (0 ≤ index ≤ size); later elements move right | — |
| `E get(int index)` | Reads the element at index | That element |
| `E set(int index, E obj)` | Replaces the element at index | The element formerly there |
| `E remove(int index)` | Removes the element at index; later elements move left | The removed element |

Worked Example 3 Inserting

### add With an Index

Predict the output.

Code

```
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
trees.add("elm");
trees.add(1, "fir");
trees.add(4, "ash");
System.out.println(trees);
System.out.println(trees.size());
```

Output

```
[pine, fir, oak, elm, ash]
5
```

1. 1 **`add(1, "fir")`** inserts at index 1; oak and elm move right (Figure 2).
2. 2 **`add(4, "ash")`** uses index 4, which equals the size at that moment, so it appends at the end. Valid insert positions are 0 through `size()`.

**Result:** The output is [pine, fir, oak, elm, ash] and 5. `add(index, obj)` inserts and shifts later elements right; an index equal to the size appends.

Common Mistake 1 · Forgetting That Insertion Shifts Indices

After `add(1, "fir")`, the element that was at index 1 is now at index 2. Any index saved before the insertion may now point at a different element. Re-read positions after inserting.

## 4 Reading and Replacing

`E get(int index)` returns the element at position `index` in the list without changing anything. `E set(int index, E obj)` replaces the element at position `index` with `obj` and returns the element formerly at that position; the size does not change.

These two methods play the roles that `a[i]` and `a[i] = v` play for arrays. The return value of `set` is often ignored, but it is useful when a program needs to know what was replaced, for example to swap two elements or to record a change.

Elements of a list of objects can also be used directly: `trees.get(0).length()` calls a `String` method on the first element. When the list holds mutable objects, calling a mutator on an element returned by `get` changes the object stored in the list, because `get` returns the reference, not a copy.

**Figure 3.** `get(int index)` returns the element at `index`; `set(int index, E obj)` replaces it and returns the element formerly at that position.

Worked Example 4 Replacing

### set Returns the Old Value

Predict the output.

Code

```
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
trees.add("elm");
String old = trees.set(0, "yew");
System.out.println(old);
System.out.println(trees);
System.out.println(trees.size());
```

Output

```
pine
[yew, oak, elm]
3
```

1. 1 **`set(0, "yew")`** replaces the element at index 0.
2. 2 **It returns the element formerly there**, "pine", which is stored in `old`.
3. 3 **The size does not change.**

**Result:** The output is pine, [yew, oak, elm], and 3. `set` replaces an element and returns the one it replaced.

Worked Example 5 Lists of numbers

### ArrayList and Autoboxing

Predict the output. Watch what `remove(1)` means.

Code

```
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(80);
scores.add(1);
scores.add(95);
int first = scores.get(0);
scores.remove(1);
System.out.println(first + scores.get(0));
System.out.println(scores);
```

Output

```
160
[80, 95]
```

1. 1 **Wrapper type.** An `ArrayList` holds object references, so a list of whole numbers is `ArrayList<Integer>`; `add(80)` autoboxes.
2. 2 **Unboxing.** `int first = scores.get(0);` unboxes 80.
3. 3 **`remove(1)` removes by index:** the element at index 1 (the value 1), not the value 1 wherever it is.
4. 4 **Result.** 80 + 80 = 160, and the list is [80, 95].

**Result:** The output is 160 and [80, 95]. Lists of numbers use `Integer` or `Double` as the element type, with autoboxing and unboxing handling conversions.

## 5 Removing Elements

`E remove(int index)` removes the element from position `index`, moving elements at position `index + 1` and higher to the left, subtracting 1 from their indices, and subtracting 1 from the size. It returns the element formerly at position `index`, so the removed value can still be used.

For an `ArrayList<Integer>`, `remove(1)` removes the element *at index 1*, not the value 1. Keeping that distinction in mind avoids a common surprise when lists hold small whole numbers.

**Figure 4.** `remove(int index)` removes the element at `index`, moves higher elements to the left, subtracts 1 from the size, and returns the removed element.

| Statement | List afterward | size() |
| --- | --- | --- |
| new ArrayList\<String>() | [] | 0 |
| add("pine"), add("oak"), add("elm") | [pine, oak, elm] | 3 |
| add(1, "fir") | [pine, fir, oak, elm] | 4 |
| set(0, "yew") | [yew, fir, oak, elm] | 4 |
| remove(1) | [yew, oak, elm] | 3 |

Worked Example 6 Removing

### remove Returns What It Took Out

Predict the output.

Code

```
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("fir");
trees.add("oak");
trees.add("elm");
String gone = trees.remove(1);
System.out.println(gone);
System.out.println(trees);
System.out.println(trees.get(1));
```

Output

```
fir
[pine, oak, elm]
oak
```

1. 1 **`remove(1)`** removes "fir" and returns it.
2. 2 **Elements shift left.** "oak" moves from index 2 to index 1, and "elm" from 3 to 2 (Figure 4).
3. 3 **Size shrinks** from 4 to 3, so `get(1)` is now "oak".

**Result:** The output is fir, [pine, oak, elm], and oak. `remove(index)` deletes an element, shifts later elements left, and returns the removed element.

Worked Example 7 Using returned values

### Serving a Waiting List in Order

A waiting list is served from the front. Predict the output.

Code

```
ArrayList<String> waiting = new ArrayList<String>();
waiting.add("table 4");
waiting.add("table 9");
waiting.add("table 2");
while (waiting.size() > 0)
{
    String next = waiting.remove(0);
    System.out.println("serving " + next + ", " + waiting.size() + " left");
}
```

Output

```
serving table 4, 2 left
serving table 9, 1 left
serving table 2, 0 left
```

1. 1 **`remove(0)`** takes the first element and returns it, so the program can use it.
2. 2 **Everything shifts left**, so the next element is always at index 0.
3. 3 **The loop condition** asks for the current size every time; when the list is empty, the loop ends.

**Result:** Three lines print, serving tables 4, 9, and 2 in order with 2, 1, and 0 left. The return value of `remove` and the changing `size()` work together to process a list from the front.

Common Mistake 2 · Removing by Value Instead of by Index

`scores.remove(1)` removes whatever is at index 1. To remove a particular value, first find its index with a traversal, then call `remove` with that index.

## 6 Indices and Element Types

The indices for an `ArrayList` start at 0 and end at the number of elements minus 1. The last element is `list.get(list.size() - 1)`. Using an index outside this range with `get`, `set`, or `remove` throws an `IndexOutOfBoundsException`; for `add(index, obj)`, the size itself is also a valid index.

Because the size changes, code must always ask the list for its current size rather than remembering an old one. After a removal, every later element has a smaller index, and the list is one shorter; after an insertion, the reverse. This is the main source of errors when lists are modified inside loops.

Worked Example 8 Invalid indices

### Reading One Past the End

What happens?

Code

```
ArrayList<String> trees = new ArrayList<String>();
trees.add("pine");
trees.add("oak");
System.out.println(trees.get(1));
System.out.println(trees.get(trees.size()));
```

1. 1 **`get(1)`** is the last element: "oak".
2. 2 **`get(trees.size())`** is `get(2)`, one past the end, so Java throws an `IndexOutOfBoundsException`.

**Result:** The program prints oak and then stops with an `IndexOutOfBoundsException`. ArrayList indices start at 0 and end at the number of elements minus 1.

Common Mistake 3 · Using size() as the Last Index

`list.get(list.size())` is always out of bounds. The last element is at `list.size() - 1`.

Common Mistake 4 · Writing length for a List

Arrays use the attribute `length`; strings use the method `length()`; an `ArrayList` uses the method `size()`. Using the wrong one does not compile.

### Four Habits for ArrayList

#### 1. Import and Type It

import java.util.ArrayList; ArrayList\<E>.

#### 2. size() Changes

Always ask for the current size.

#### 3. Inserts Shift Right, Removes Shift Left

Indices move after every add or remove.

#### 4. set and remove Return Values

The replaced or removed element.

Core Synthesis

An `ArrayList` object is mutable in size and contains object references. The constructor `ArrayList()` constructs an empty list. The generic type `ArrayList<E>`, where `E` specifies the element type, is preferred because it allows the compiler to find errors that would otherwise be found at run time. The class is part of the `java.util` package and must be imported. `size()` returns the number of elements; `add(E obj)` appends and returns `true`; `add(int index, E obj)` inserts, moving later elements right; `get(int index)` returns an element; `set(int index, E obj)` replaces an element and returns the old one; and `remove(int index)` removes an element, moving later elements left, and returns it. Indices start at 0 and end at the number of elements minus 1.

FiveStudy AP® Computer Science A Study Guide · Data Collections · ArrayList Methods Back to top ↑
