FRQ Type 3: Data Analysis with ArrayList

Practice these in the app

The third free-response question gives you a class that keeps an ArrayList of data, usually objects of a second class that describes them through a few getter methods. You write one method that reads the list and answers a question about it: a count, the best entry, a total, or a new list of the entries that qualify.
It is always the third of the exam's four free-response questions: one method worth 5 of their 25 points. Some older questions in the index use a plain array instead of an ArrayList; the loops are the same with [i] and length in place of get(i) and size().

The setup

The examples on this page use a dock that rents out rowboats. Each rental is an object of a provided class with two getters, the kind of class the 2026 question provided:
public class Rental
{
    /** Returns the name of the boat that was rented */
    public String getBoatName()
    { /* implementation not shown */ }

    /** Returns the length of the rental in minutes, always > 0 */
    public int getMinutes()
    { /* implementation not shown */ }
}

public class RowboatDock
{
    /** The rentals of one day, in order */
    private ArrayList<Rental> rentals;

    /* methods to be written */
}
The provided class's instance variables are private, so the only way to read a rental is through its getters: r.getMinutes(), never r.minutes. The examples below use a day with five rentals: Puffin for 45 minutes, Loon for 30, Petrel for 75, Puffin again for 90, and Loon again for 21.
Some years keep a list of plain values instead: an ArrayList<Double> in 2023 and an ArrayList<String> in 2024. Those are read with get(i) or an enhanced for loop directly, and Strings are compared with equals.

Visiting every element

An enhanced for loop visits every element with no index and no chance of a bounds error:
int total = 0;
for (Rental r : rentals)
{
    total += r.getMinutes();
}
Use it whenever the answer doesn't depend on positions. The 2026 guide says that an enhanced for loop accesses all the elements by definition, so it earns the point for accessing the elements of that list. An indexed loop is needed only when positions matter, such as comparing an element with the one before it. Then the loop runs from 0 while i < rentals.size() and reads rentals.get(i).

Counting and totals

A count or a total starts at 0 before the loop and changes inside an if:
public int minutesFor(String name)
{
    int total = 0;
    for (Rental r : rentals)
    {
        if (r.getBoatName().equals(name))
        {
            total += r.getMinutes();
        }
    }
    return total;
}
For the five rentals, minutesFor("Puffin") returns 135. Compare the names with equals: == asks whether two Strings are the same object, and it cost the algorithm point in 2026.
An average adds up a total and divides by a count, both int, so cast before dividing: (double) total / rentals.size() is 52.2 for the five rentals, and without the cast it's 52. If the list can be empty, the question says what to return, and dividing by 0 must not happen.

The best entry

Finding the largest or smallest keeps the best entry so far and replaces it when a better one appears. When the precondition says the list is not empty, the first element is a safe starting point:
public String longestRental()
{
    Rental best = rentals.get(0);
    for (Rental r : rentals)
    {
        if (r.getMinutes() > best.getMinutes())
        {
            best = r;
        }
    }
    return best.getBoatName();
}
It returns Puffin, for the 90-minute rental. Keeping the whole object, not only its minutes, means the name is at hand at the end. Without a "not empty" precondition, start from a value every real entry beats instead, such as -1 for a count that can be 0. A largest value started at 0 is right when every value is 0, but nothing ever replaces it, so a name kept beside it is never recorded. With > a tie keeps the earlier entry; with >= it takes the later one. Read which one the question wants.

A new list of the entries that qualify

A method that returns a list builds a new one, adds to it inside the loop, and returns it after the loop. It never adds to or removes from the instance variable:
public ArrayList<String> boatsOver(int limit)
{
    ArrayList<String> result = new ArrayList<String>();
    for (Rental r : rentals)
    {
        if (r.getMinutes() > limit)
        {
            result.add(r.getBoatName());
        }
    }
    return result;
}
For a limit of 40 it returns [Puffin, Petrel, Puffin], in list order. When nothing qualifies, it returns an empty list, not null. Copy the strictness of the question word for word: "more than" is >, and in 2026 writing >= for it lost the point for the comparison. Writing ArrayList<Rental> result = rentals; does not make a new list: both names refer to the same one, so every add or remove on result changes rentals.
When each name should appear only once, check the result before adding. contains is not on the Quick Reference, so a loop over the result with equals is the safe way. For the boats rented that day, each named once, the body of the loop over the rentals is:
boolean found = false;
for (String name : result)
{
    if (name.equals(r.getBoatName()))
    {
        found = true;
    }
}
if (!found)
{
    result.add(r.getBoatName());
}
That version returns [Puffin, Loon, Petrel]. The flag is set to false for each rental, before the inner loop, and the add comes after the inner loop ends. With the add inside the inner loop, nothing is ever added: the result starts empty, so the inner loop never runs.

Neighbors and runs

Comparing each element with the one before it needs an index, and the loop starts at 1 so that i - 1 is always a real position. This method finds the first rental shorter than the one before it:
public int firstDrop()
{
    for (int i = 1; i < rentals.size(); i++)
    {
        if (rentals.get(i).getMinutes() < rentals.get(i - 1).getMinutes())
        {
            return i;
        }
    }
    return -1;
}
For the five rentals it returns 1: the Loon's 30 minutes follow the Puffin's 45. Starting at 0 would read position -1 and throw an exception. The return inside the loop is correct here, because the first drop is the answer, and so is the -1 after the loop for a list with no drop. The same holds for a method that asks whether every neighbor passes a test: it returns false inside the loop as soon as one pair fails, and true only after the loop. The early return that costs points is one that ends the loop before every element has had its say. Some questions track a run of neighbors that meet a condition, such as the longest stretch of entries above a limit. Keep the current run's length, set it back to 0 when the run breaks, and update the longest inside the loop, so a run that lasts to the last element still counts.

Two lists

The 2026 question held two lists and matched their entries on an ID. Two nested loops pair every entry of one list with every entry of the other, and the condition checks that the IDs match before comparing the numbers. With a morning list and an evening list, each holding a boat at most once:
int count = 0;
for (Rental am : morning)
{
    for (Rental pm : evening)
    {
        if (am.getBoatName().equals(pm.getBoatName())
            && pm.getMinutes() > am.getMinutes())
        {
            count++;
        }
    }
}
Without the name test, the method compares every morning rental with every evening rental, whatever the boat. The 2026 guide gave the point for the comparison to a response like that and took the algorithm point instead. Pairs within one list start the inner loop at j = i + 1, so no element is paired with itself and no pair is counted twice.

Leave the list unchanged

The 2026 question states that both lists are unchanged after the method runs, as 2022, 2024, and part (b) of 2025 did before it. Calling add, remove, or set on it, or changing one of its objects, costs the algorithm point. Older exams asked for elements to be removed, and those answers needed care: after remove(i), the next element takes position i, so a loop that always adds 1 to i skips it. That shape no longer appears, but an answer that removes elements to make a count easier now loses the algorithm point.

Scoring notes

  • In 2026 the five points were: accessing every element of the lists with no bounds errors; calling both getters on an element; the comparison the question asks for; giving a count a starting value and adding to it inside an if, in the loop; and the algorithm point, returning the correct count.
  • [] on an ArrayList costs the first point and nothing else, because that point already checks it.
  • A comparison with the wrong strictness, such as >= for "more than," costs the point for the comparison.
  • The algorithm point was lost in 2026 for an early return, for == on Strings, for changing either list, for printing the count instead of returning it, and for not returning it. It was kept with a loop that stopped one element early or late.
  • Through 2025 a question had two parts and often a separate point for declaring the result list (2019, 2021, 2024, 2025). The 2026 question returned a count, and its one algorithm point required returning it.
  • The general rules ignore length written for size, a local variable used without being declared, and a missing semicolon or brace where the indentation shows the structure.

Common traps

  • list[i] instead of list.get(i).
  • Reading a private instance variable of the provided class instead of calling its getter.
  • == instead of equals on an ID or a name.
  • A return inside the loop, in the else of a search, so only the first element is ever checked.
  • A count or total set to 0 inside the loop.
  • A largest value that starts at 0, which never records a name when every value is 0, or a smallest that starts at 0, which nothing is ever below.
  • Returning the number when the question asks for the name, or the index when it asks for the object.
  • int division in an average.
  • A loop over neighbors that runs to the last index and reads past it, or starts at 0 and reads before the first.
  • In a list without repeats, the flag set once before the outer loop, or the add inside the inner loop.
  • Removing elements from the list, or returning the list itself instead of a new one.

A full question

An athlete's total is spread over the list, so the method adds it up for each routine it visits, with an inner loop over the whole list, and keeps the best total found so far:
public String topAthlete()
{
    String best = "";
    int bestTotal = -1;
    for (Routine r : routines)
    {
        int total = 0;
        for (Routine other : routines)
        {
            if (other.getAthlete().equals(r.getAthlete()))
            {
                total += other.getPoints();
            }
        }
        if (total > bestTotal)
        {
            bestTotal = total;
            best = r.getAthlete();
        }
    }
    return best;
}
Three details carry the points. The inner total starts at 0 inside the outer loop, once for each routine, so each athlete's total is counted fresh. The test is >, so a later athlete with an equal total, and the same athlete met again later in the list, never replaces the first; that is the tie rule. And bestTotal starts at -1, below any real total: a start of 0 would return the empty String for a meet where every routine earned 0 points. The athletes' totals are computed again for each of their routines, which is wasteful but correct, and the guides don't score efficiency.
A scoring guide for this question, written in the style of the 2026 guidelines, could read:
PointEarned forNotes
1Accesses all elements of routines (no bounds errors)Not earned for routines[i] or a loop that never reads an element
2Calls getAthlete and getPoints on elements of the listNot earned for reading the instance variables directly
3Compares athletes' names with equals to total one athlete's pointsNot earned for == on the names
4Keeps the greatest total found so far and the name that goes with itEarned even if the tie rule is wrong
5 (algorithm)Returns the correct name, ties to the earliest first routine, with routines unchangedNot earned for an early return, for changing the list, or for printing the name
Here is the method in a program with the example's routines and a second meet where every routine earned 0. Press Run, then change the points, add routines, or start bestTotal at 0 and run the second meet again.
import java.util.ArrayList;

public class Main
{
    public static void main(String[] args)
    {
        ArrayList<Routine> list = new ArrayList<Routine>();
        list.add(new Routine("Lucia", 7));
        list.add(new Routine("Haruto", 9));
        list.add(new Routine("Lucia", 6));
        list.add(new Routine("Koa", 9));
        list.add(new Routine("Haruto", 4));

        TrampolineMeet meet = new TrampolineMeet(list);
        System.out.println("Top athlete: " + meet.topAthlete());
        System.out.println("Routines still in the list: " + list.size());

        ArrayList<Routine> zeros = new ArrayList<Routine>();
        zeros.add(new Routine("Bastien", 0));
        zeros.add(new Routine("Odile", 0));
        System.out.println("All zero: " + new TrampolineMeet(zeros).topAthlete());
    }
}
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Released exam index

Every released question that reads through a list of data, 2010 to 2026, including the ones built on a plain array. Before 2026 most of them had a second part, and several of those parts added to or removed from the list.
ExamClassesKey features
2010 Q1MasterOrder, CookieOrderTotal boxes over a list of orders; remove one variety and return how many boxes were removed
2010 Q3Trail (array)Whether the largest minus the smallest over a range of indexes is at most 10; whether 3 or more neighbors differ by at least 30, up or down
2011 Q1Sound (array)Clamp every value to between -limit and limit and count the changes; remove leading zeros into a new array
2011 Q3(a)FuelDepot, FuelTankIndex of the tank with the lowest level at or below a threshold, with a fallback
2012 Q1ClimbingClub, ClimbInfoAdd climbs at the end, then in alphabetical order; say whether a given distinct-names count still works
2012 Q3HorseBarn (array)Search for a name, skipping empty stalls; compact the horses to the front
2013 Q1MusicDownloads, DownloadInfoFind a title or return null; add a title or raise its count
2013 Q2TokenPass (array)Random tokens in the constructor; hand out a player's tokens around the board with %
2014 Q1(b)Static list methodScramble each word with part (a) and remove the words it leaves unchanged
2015 Q3SparseArray, SparseArrayEntryLook up a value by row and column, or 0; remove a column and shift the later ones
2016 Q2(c)SystemLog, LogMessageRemove the messages that contain a word and return them in a new list
2016 Q4StringFormatterTotal letters in a list of words; gap width by integer division; pad words into a line
2017 Q1DigitsBuild a list of a number's digits with % and /; whether each digit is greater than the one before it
2018 Q2WordPairList, WordPairBuild every pair of words with the first before the second; count pairs of equal words
2019 Q3DelimitersCopy the delimiters from an array into a list; check that the open and close delimiters balance
2021 Q3ClubMembers, MemberInfoAdd members from an array; remove graduates and return those in good standing
2022 Q3ReviewAnalysis, Review (array)Average rating as a double; the comments containing "!", numbered, with a period added where missing
2023 Q3WeatherDataRemove temperatures outside a range; the longest run above a threshold
2024 Q3WordCheckerEach word contains the one before it; the words that start with a target, with the target removed
2025 Q3Round, Competitor, MatchBuild the competitor list from names and ranks; pair the best remaining with the worst
2026 Q3Attendance, CourseRecordTwo lists matched on student ID; count the students with more absences in history than in math