---
title: "ArrayList Algorithms | FiveStudy"
description: "The accumulator family on ArrayLists: sum, max, count, transform with set, and backward pruning."
url: https://fivestudy.com/guides/arraylist-algorithms
---

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

# ArrayList Algorithms

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Data Collections

AP® Computer Science A · Data Collections

# Implementing *ArrayList* Algorithms

The standard traversal algorithms applied to ArrayList objects: minimums, maximums, sums, and averages; property checks and counts; consecutive pairs and duplicates; shifting, rotating, and reversing; inserting and deleting; and traversing several collections at once.

1. Familiar Algorithms 2. Checking Properties 3. Pairs and Duplicates 4. Rotating and Reversing 5. Inserting and Deleting 6. Several Collections

Big Picture

There are standard `ArrayList` algorithms that utilize traversals to determine a minimum or maximum value; compute a sum or average; determine if at least one element, or all elements, have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements; shift or rotate elements left or right; reverse the order of the elements; insert elements; and delete elements. Some algorithms require multiple `String`, array, or `ArrayList` objects to be traversed simultaneously.

## 1 Familiar Algorithms With List Syntax

Most `ArrayList` algorithms are the array algorithms with new syntax: `list.get(i)` replaces `a[i]`, `list.set(i, v)` replaces assignment to an element, and `list.size()` replaces `a.length`. Enhanced `for` loops work the same way for reading every element.

A minimum or maximum starts from an actual element, `list.get(0)`, and replaces it whenever a smaller or larger element appears. A sum adds every element; an average divides that sum by `list.size()`. For a list of `Integer` or `Double` objects, unboxing turns each element into a primitive for the arithmetic.

| Algorithm | ArrayList pattern |
| --- | --- |
| Minimum or maximum | Start at `list.get(0)`; compare each element |
| Sum or average | Add each element; divide by `list.size()` |
| At least one has a property | Return true at the first match; false after the loop |
| All have a property | Return false at the first failure; true after the loop |
| Count with a property | Add 1 for each match |
| Consecutive pairs | `i < list.size() - 1`; compare get(i) and get(i + 1) |
| Duplicates | Nested loops, inner index starting at i + 1 |
| Shift or rotate | remove at one end, add at the other |
| Reverse | Swap get(i) and get(size − 1 − i) with set, for i < size / 2 |
| Insert | Find the index, then `add(index, value)` |
| Delete | Traverse backward and `remove(i)` each match |

Worked Example 1 Minimum, maximum, average

### Summarizing a List

Predict the output.

Code

```
ArrayList<Double> temps = new ArrayList<Double>();
temps.add(18.5);
temps.add(22.0);
temps.add(16.5);
temps.add(21.0);

double max = temps.get(0);
double min = temps.get(0);
double sum = 0.0;
for (double t : temps)
{
    sum += t;
    if (t > max)
    {
        max = t;
    }
    if (t < min)
    {
        min = t;
    }
}
System.out.println(max + " " + min);
System.out.println(sum / temps.size());
```

Output

```
22.0 16.5
19.5
```

1. 1 **Start from a real element.** `max` and `min` both begin at `temps.get(0)`.
2. 2 **Unboxing in the loop.** `for (double t : temps)` unboxes each `Double`.
3. 3 **Average.** 78.0 / 4 = 19.5; divide by `size()`, not a fixed number.

**Result:** The output is 22.0 16.5 and 19.5. Minimum, maximum, sum, and average work on an ArrayList exactly as on an array, with `get` and `size()`.

Common Mistake 1 · Assuming the List Has Elements

An empty list has no element 0, so `list.get(0)` throws an `IndexOutOfBoundsException`, and dividing a sum by `list.size()` divides by zero. When a list might be empty, check `list.size() > 0` before computing a minimum, maximum, or average.

## 2 Checking Properties

Three closely related algorithms test elements against a condition. To determine whether **at least one** element has a property, return `true` as soon as one is found, and return `false` only after the loop finishes. To determine whether **all** elements have it, return `false` at the first element that fails, and `true` after the loop. To find **how many** elements have it, count matches through the whole list.

The most common mistake is returning from the loop too soon: an "all" check that returns `true` inside the loop after one passing element has not looked at the rest. The answer that requires seeing every element always belongs after the loop.

**Figure 1.** Checking whether at least one element, all elements, or how many elements have a property uses the same traversal with a different result.

Worked Example 2 Checking a property

### At Least One, All, and How Many

Three methods ask three questions about the same list (Figure 1).

Code

```
public static boolean atLeastOne(ArrayList<Integer> list, int min)
{
    for (int v : list)
    {
        if (v >= min)
        {
            return true;
        }
    }
    return false;
}

public static boolean allAtLeast(ArrayList<Integer> list, int min)
{
    for (int v : list)
    {
        if (v < min)
        {
            return false;
        }
    }
    return true;
}

public static int countAtLeast(ArrayList<Integer> list, int min)
{
    int count = 0;
    for (int v : list)
    {
        if (v >= min)
        {
            count++;
        }
    }
    return count;
}
```

Output

```
true
false
3
```

1. 1 **At least one:** return `true` at the first element that passes; `false` only after checking them all.
2. 2 **All:** return `false` at the first element that fails; `true` only after checking them all.
3. 3 **How many:** no early return; every passing element adds 1.

**Result:** The output is true, false, and 3. The three property checks differ only in when they stop and what they return.

## 3 Pairs and Duplicates

Accessing all consecutive pairs of elements compares each element with the next one: `list.get(i)` and `list.get(i + 1)`. Because the last element has no next element, the loop runs while `i < list.size() - 1`. A list of five elements has four consecutive pairs. Pair algorithms find rises and falls, check whether a list is in order, or find the largest jump between neighbors.

Determining the presence or absence of duplicate elements compares each element with every element after it, using nested loops in which the inner index starts at `i + 1`. Starting there means no element is compared with itself and each pair is checked only once. String elements are compared with `equals`.

**Figure 2.** Accessing all consecutive pairs compares `get(i)` with `get(i + 1)`, so the index stops one before the last element.

Worked Example 3 Consecutive pairs

### Counting the Rises

Count how many times a value is larger than the one before it.

Code

```
ArrayList<Integer> steps = new ArrayList<Integer>();
steps.add(3);
steps.add(5);
steps.add(4);
steps.add(8);
steps.add(9);

int rises = 0;
for (int i = 0; i < steps.size() - 1; i++)
{
    if (steps.get(i + 1) > steps.get(i))
    {
        rises++;
    }
}
System.out.println(rises);
```

Output

```
3
```

1. 1 **Bounds.** `i` stops at `size() - 2`, so `get(i + 1)` is always valid.
2. 2 **Pairs.** 3→5 rises, 5→4 falls, 4→8 rises, 8→9 rises.

**Result:** The output is 3. Accessing consecutive pairs uses `get(i)` and `get(i + 1)` with a loop that ends one element early.

Worked Example 4 Duplicates

### Is Any Value Repeated?

Compare every element with every element after it.

Code

```
ArrayList<String> stops = new ArrayList<String>();
stops.add("LHR");
stops.add("SFO");
stops.add("ICN");
stops.add("SFO");

boolean repeated = false;
for (int i = 0; i < stops.size(); i++)
{
    for (int j = i + 1; j < stops.size(); j++)
    {
        if (stops.get(i).equals(stops.get(j)))
        {
            repeated = true;
            System.out.println("repeat: " + stops.get(j) + " at " + i + " and " + j);
        }
    }
}
System.out.println(repeated);
```

Output

```
repeat: SFO at 1 and 3
true
```

1. 1 **Inner loop starts at `i + 1`**, so each pair is compared once and no element is compared with itself.
2. 2 **`equals`** compares the text of two strings.

**Result:** The output is repeat: SFO at 1 and 3, then true. Detecting duplicates uses nested traversals over the same list.

Common Mistake 2 · Running a Pair Loop to the Last Index

With `i < list.size()`, the final pass calls `list.get(list.size())` through `get(i + 1)` and throws an `IndexOutOfBoundsException`. Pair loops end at `list.size() - 1`.

Common Mistake 3 · Comparing Two Integer Elements With ==

Elements of an `ArrayList<Integer>` are references, and `==` on two references asks whether they are the same object, not whether they hold the same number. Store the elements in `int` variables first, for example `int a = list.get(i);`, and compare those. Relational operators such as `<` and `>` unbox automatically.

## 4 Shifting, Rotating, and Reversing

Because an `ArrayList` shifts elements itself, rotating is short. To rotate right by one, remove the last element and insert it at index 0; to rotate left by one, remove the element at index 0 and append it with `add`. Shifting without wrapping around works the same way, except the removed element is discarded and, if the size must stay the same, a placeholder value is added at the other end.

Reversing the order of the elements swaps pairs from the outside in: index 0 with the last index, index 1 with the second-to-last, and so on, for `i < list.size() / 2`. Each swap uses a temporary variable with `get` and `set`. Since `set` never changes the size, the loop bound stays correct throughout.

**Figure 3.** With an `ArrayList`, rotating right removes the last element and inserts it at index 0; `add` shifts the others automatically.

Worked Example 5 Rotating

### Rotate Right, Then Left

Use `remove` and `add` to rotate the list (Figure 3).

Code

```
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10);
nums.add(20);
nums.add(30);
nums.add(40);
nums.add(50);

int last = nums.remove(nums.size() - 1);
nums.add(0, last);
System.out.println(nums);
int first = nums.remove(0);
nums.add(first);
System.out.println(nums);
```

Output

```
[50, 10, 20, 30, 40]
[10, 20, 30, 40, 50]
```

1. 1 **Right by one.** Remove the last element and insert it at index 0; `add(0, ...)` shifts everything else right.
2. 2 **Left by one.** Remove the first element and append it; `remove(0)` shifts everything else left.
3. 3 **No temporary array** is needed, because the list moves elements itself.

**Result:** The output is [50, 10, 20, 30, 40] and then [10, 20, 30, 40, 50]. ArrayList methods do the shifting that an array version must write by hand.

Worked Example 6 Reversing

### Swapping From Both Ends With set

Predict the output.

Code

```
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(12);
nums.add(7);
nums.add(19);
nums.add(4);
nums.add(15);

for (int i = 0; i < nums.size() / 2; i++)
{
    int j = nums.size() - 1 - i;
    int temp = nums.get(i);
    nums.set(i, nums.get(j));
    nums.set(j, temp);
}
System.out.println(nums);
```

Output

```
[15, 4, 19, 7, 12]
```

1. 1 **Pairs from the outside in.** Index 0 swaps with 4, and 1 with 3; the middle element stays.
2. 2 **`set` keeps the size the same**, so the loop bound `size() / 2` is stable.

**Result:** The output is [15, 4, 19, 7, 12]. Reversing in place swaps pairs with `get` and `set`, using a temporary variable.

| Task | Array version | ArrayList version |
| --- | --- | --- |
| Insert at index k | Make room by shifting elements right by hand; length cannot grow | `list.add(k, value)` |
| Delete at index k | Shift elements left by hand; a leftover slot remains | `list.remove(k)` |
| Rotate right by one | Save the last element, shift the rest, store it at 0 | `list.add(0, list.remove(list.size() - 1))` |
| Reverse | Swap with a temporary variable | Swap with get, set, and a temporary variable |

## 5 Inserting and Deleting

Inserting an element at a particular position uses `add(index, value)`. Keeping a list in order first finds the position, the index of the first element larger than the new value, then inserts there. The search loop must test `pos < list.size()` before `list.get(pos)`, so that a value larger than every element stops at the end and is appended instead of causing an exception.

Deleting elements that meet a condition calls `remove(i)` for each match. To avoid skipping the element that slides into a removed position, traverse backward, or advance the index only when nothing was removed. Inserting during a forward traversal has the reverse problem: the inserted element is visited again on the next pass, so the index must move past it.

| pos | list.get(pos) | get(pos) < 17? | Action |
| --- | --- | --- | --- |
| 0 | 5 | true | pos becomes 1 |
| 1 | 12 | true | pos becomes 2 |
| 2 | 20 | false | loop ends |
| — | — | — | add(2, 17) → [5, 12, 17, 20, 31] |

Worked Example 7 Inserting

### Keeping a List in Order

Insert each value at the position that keeps the list sorted.

Code

```
public static void insertInOrder(ArrayList<Integer> list, int value)
{
    int pos = 0;
    while (pos < list.size() && list.get(pos) < value)
    {
        pos++;
    }
    list.add(pos, value);
}
```

Output

```
[2, 5, 12, 17, 20, 31, 40]
```

1. 1 **Find the position.** Move `pos` past every element smaller than the new value (trace below).
2. 2 **The bounds check comes first.** For 40, `pos` reaches `size()`; short-circuit `&&` stops before `get(pos)` would fail, and `add(size(), 40)` appends.
3. 3 **For 2,** the loop never runs and the value goes to index 0.

**Result:** The output is [2, 5, 12, 17, 20, 31, 40]. Inserting into a sorted list finds the first larger element and uses `add(index, value)`.

Worked Example 8 Deleting

### Removing Every Negative Reading

Delete all negative values without skipping any.

Code

```
ArrayList<Integer> readings = new ArrayList<Integer>();
readings.add(4);
readings.add(-1);
readings.add(-1);
readings.add(7);
readings.add(0);
readings.add(-1);
readings.add(9);

for (int i = readings.size() - 1; i >= 0; i--)
{
    if (readings.get(i) < 0)
    {
        readings.remove(i);
    }
}
System.out.println(readings);
```

Output

```
[4, 7, 0, 9]
```

1. 1 **Backward traversal.** Removing at `i` shifts only elements that were already checked.
2. 2 **Adjacent matches** (the two −1 values at indices 1 and 2) are both removed.

**Result:** The output is [4, 7, 0, 9]. Deleting elements that meet a condition traverses backward so no element is skipped.

## 6 Traversing Several Collections at Once

Some algorithms require multiple `String`, array, or `ArrayList` objects to be traversed simultaneously. When the collections line up position by position, one index serves them all: `code.substring(i, i + 1)` and `guess.get(i)` refer to the same position. Other algorithms copy elements from one collection into another, or keep a separate index for each collection.

The loop bound must be valid for every collection being traversed. If the lengths might differ, loop to the smaller length, or the shorter collection will be read past its end. Writing out the index and the elements from each collection on each pass is the clearest way to trace these algorithms.

**Figure 4.** Some algorithms traverse a `String`, an array, or an `ArrayList` simultaneously, using one index for all of them.

Worked Example 9 Two collections at once

### Comparing a Code With a Guess

A `String` and an `ArrayList` are traversed together (Figure 4).

Code

```
String code = "RGBY";
ArrayList<String> guess = new ArrayList<String>();
guess.add("R");
guess.add("B");
guess.add("B");
guess.add("Y");
int exact = 0;
for (int i = 0; i < guess.size(); i++)
{
    if (code.substring(i, i + 1).equals(guess.get(i)))
    {
        exact++;
    }
}
System.out.println(exact + " of " + code.length());
```

Output

```
3 of 4
```

1. 1 **One index, two collections.** `i` selects a one-letter substring of `code` and the element of `guess` at the same position.
2. 2 **Matches.** Positions 0, 2, and 3 agree; position 1 ("G" versus "B") does not.

**Result:** The output is 3 of 4. Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously with a shared index.

Common Mistake 4 · Assuming Collections Have the Same Length

A loop bounded by one collection's size can run past the end of another. Before traversing two collections together, confirm their lengths match or loop to the smaller of the two.

### Four Habits for List Algorithms

#### 1. Start From a Real Element

get(0) for minimum and maximum.

#### 2. Decide After the Loop

"All" and "none" need every element.

#### 3. Let the List Shift

add and remove move elements for you.

#### 4. Check Every Bound

Pairs stop early; paired collections share a valid bound.

Core Synthesis

There are standard `ArrayList` algorithms that utilize traversals to determine a minimum or maximum value; compute a sum or average; determine if at least one element has a particular property; determine if all elements have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements; shift or rotate elements left or right; reverse the order of the elements; insert elements; and delete elements. Some algorithms require multiple `String`, array, or `ArrayList` objects to be traversed simultaneously.

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