AP Computer Science A · Study guide

ArrayList Algorithms

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.

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.

1Familiar 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.

AlgorithmArrayList pattern
Minimum or maximumStart at list.get(0); compare each element
Sum or averageAdd each element; divide by list.size()
At least one has a propertyReturn true at the first match; false after the loop
All have a propertyReturn false at the first failure; true after the loop
Count with a propertyAdd 1 for each match
Consecutive pairsi < list.size() - 1; compare get(i) and get(i + 1)
DuplicatesNested loops, inner index starting at i + 1
Shift or rotateremove at one end, add at the other
ReverseSwap get(i) and get(size − 1 − i) with set, for i < size / 2
InsertFind the index, then add(index, value)
DeleteTraverse 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. 1Start from a real element. max and min both begin at temps.get(0).
  2. 2Unboxing in the loop. for (double t : temps) unboxes each Double.
  3. 3Average. 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.

2Checking 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. 1At least one: return true at the first element that passes; false only after checking them all.
  2. 2All: return false at the first element that fails; true only after checking them all.
  3. 3How 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.

3Pairs 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. 1Bounds. i stops at size() - 2, so get(i + 1) is always valid.
  2. 2Pairs. 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. 1Inner loop starts at i + 1, so each pair is compared once and no element is compared with itself.
  2. 2equals 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.

4Shifting, 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. 1Right by one. Remove the last element and insert it at index 0; add(0, ...) shifts everything else right.
  2. 2Left by one. Remove the first element and append it; remove(0) shifts everything else left.
  3. 3No 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. 1Pairs from the outside in. Index 0 swaps with 4, and 1 with 3; the middle element stays.
  2. 2set 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.
TaskArray versionArrayList version
Insert at index kMake room by shifting elements right by hand; length cannot growlist.add(k, value)
Delete at index kShift elements left by hand; a leftover slot remainslist.remove(k)
Rotate right by oneSave the last element, shift the rest, store it at 0list.add(0, list.remove(list.size() - 1))
ReverseSwap with a temporary variableSwap with get, set, and a temporary variable

5Inserting 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.

poslist.get(pos)get(pos) < 17?Action
05truepos becomes 1
112truepos becomes 2
220falseloop 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. 1Find the position. Move pos past every element smaller than the new value (trace below).
  2. 2The bounds check comes first. For 40, pos reaches size(); short-circuit && stops before get(pos) would fail, and add(size(), 40) appends.
  3. 3For 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. 1Backward traversal. Removing at i shifts only elements that were already checked.
  2. 2Adjacent 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.

6Traversing 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. 1One index, two collections. i selects a one-letter substring of code and the element of guess at the same position.
  2. 2Matches. 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.