AP CSA Unit 5: Data Collections II

ArrayLists and 2D arrays extend the collection skills from Unit 4. Students learn when a collection should resize, when a grid is better than a list, and how AP-style algorithms search, filter, count, remove, and traverse data.

1. Big Idea: Collections Have Shape

Unit 4 introduced arrays: fixed-size collections where each value has an index. Unit 5 adds two important collection types:

ArrayList

A resizable one-dimensional collection of objects. Use it when the number of items may grow or shrink.

ArrayList<String> names = new ArrayList<String>();
names.add("Mia");
names.add("Alex");

Analogy: an expandable filing cabinet. You can insert, remove, and reorganize files.

2D Array

A fixed-size grid with rows and columns. Use it when the data naturally fits a table, board, image, map, or heat grid.

int[][] grid = new int[3][4];
grid[0][0] = 7;

Analogy: a spreadsheet or seating chart.

AP exam connection: ArrayLists are often tested through adding, removing, filtering, and object collections. 2D arrays are tested through nested traversals, row/column logic, and grid algorithms.

2. ArrayLists: Resizable Object Collections

An ArrayList stores objects and can change size while the program runs.

import java.util.ArrayList;

ArrayList<String> events = new ArrayList<String>();
events.add("100m");
events.add("Long Jump");
events.add("Shot Put");
AP warning: ArrayLists store objects, not primitive values directly. Java uses wrapper classes like Integer and Double when you want a list of numbers.

Primitive array

int[] scores = {85, 92, 77};

ArrayList with wrapper class

ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(85);
scores.add(92);
scores.add(77);
Why can an ArrayList grow when an array cannot?

An array has a fixed length once it is created. An ArrayList manages resizing behind the scenes, so the programmer can focus on adding and removing objects.

3. Essential ArrayList Methods

MethodPurposeExampleAP Trap
add(obj)Adds to the endlist.add("A");Size increases by 1
add(index, obj)Inserts at indexlist.add(1, "B");Items at that index and after shift right
get(index)Reads a valuelist.get(0)Does not remove or change it
set(index, obj)Replaces a valuelist.set(0, "C")Size does not change
remove(index)Removes and returns valuelist.remove(2)Items after it shift left
size()Returns number of elementslist.size()Use size(), not length

Common Syntax Comparison

Array

arr.length
arr[i]

ArrayList

list.size()
list.get(i)

4. Removing Items Safely

Removal is one of the most common AP ArrayList traps because removing an item shifts everything after it left.

Risky forward removal: this can skip values.
for (int i = 0; i < scores.size(); i++) {
    if (scores.get(i) < 70) {
        scores.remove(i);
    }
}

Safer Pattern: Traverse Backward

for (int i = scores.size() - 1; i >= 0; i--) {
    if (scores.get(i) < 70) {
        scores.remove(i);
    }
}
Analogy: removing files from a folder. If you remove one from the middle, everything behind it slides forward. Walking backward prevents you from skipping the next file.
Why does backward traversal prevent skipped elements?

When you remove an item, only elements after that index shift. If you are moving backward, those shifted elements are already behind you, so your next index still points to an unchecked element.

5. 2D Arrays: Rows and Columns

A 2D array is an array of arrays. In AP CSA, you usually think of it as a grid.

int[][] temps = {
    {72, 74, 75, 73},
    {69, 70, 71, 72},
    {80, 82, 79, 78}
};

System.out.println(temps[0][2]); // 75
ExpressionMeaning
temps.lengthNumber of rows
temps[0].lengthNumber of columns in row 0
temps[r][c]Value at row r, column c
Analogy: rows are floors in a hotel, columns are rooms on each floor. grid[2][3] means floor 2, room 3.

6. 2D Array Traversals

Row-Major Traversal

This is the most common traversal: process one full row, then move to the next row.

for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

Column Traversal

Useful for column sums and vertical patterns. This assumes a rectangular array.

for (int c = 0; c < grid[0].length; c++) {
    for (int r = 0; r < grid.length; r++) {
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

Common 2D Algorithms

Sum All Values

int total = 0;
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        total += grid[r][c];
    }
}

Row Sum

int rowTotal = 0;
int row = 1;
for (int c = 0; c < grid[row].length; c++) {
    rowTotal += grid[row][c];
}

Column Sum

int colTotal = 0;
int col = 2;
for (int r = 0; r < grid.length; r++) {
    colTotal += grid[r][col];
}

Find Maximum

int max = grid[0][0];
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        if (grid[r][c] > max) {
            max = grid[r][c];
        }
    }
}

7. Interactive IDE Examples

Run each example, then modify the data. Students should predict the result before pressing run.

Example A: Track Performance ArrayList

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Double> times = new ArrayList<Double>();
        times.add(12.4);
        times.add(11.9);
        times.add(13.1);
        times.add(11.7);

        double fastest = times.get(0);
        for (int i = 1; i < times.size(); i++) {
            if (times.get(i) < fastest) {
                fastest = times.get(i);
            }
        }

        System.out.println("Fastest time: " + fastest);
    }
}

Example B: Heat Map 2D Array

public class Main {
    public static void main(String[] args) {
        int[][] heat = {
            {72, 74, 75, 73},
            {69, 70, 71, 72},
            {80, 82, 79, 78}
        };

        int total = 0;
        int count = 0;

        for (int r = 0; r < heat.length; r++) {
            for (int c = 0; c < heat[r].length; c++) {
                total += heat[r][c];
                count++;
            }
        }

        System.out.println("Average heat: " + (double) total / count);
    }
}

8. AP Tracing Challenges

1. What prints?
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add(1, "C");
System.out.println(list);

Answer: [A, C, B]. The inserted value shifts B right.

2. What prints?
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(7);
nums.set(1, 9);
System.out.println(nums.get(1));

Answer: 9. set replaces the item but does not change the size.

3. What prints?
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
System.out.println(grid.length);
System.out.println(grid[0].length);

Answer: 2 then 3. There are 2 rows and 3 columns.

4. What is total?
int[][] grid = {{2, 4}, {6, 8}};
int total = 0;
for (int r = 0; r < grid.length; r++) {
    total += grid[r][0];
}

Answer: 8. The loop adds the first column: 2 + 6.

5. What values remain?
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(2); nums.add(3); nums.add(4); nums.add(5);
for (int i = nums.size() - 1; i >= 0; i--) {
    if (nums.get(i) % 2 == 0) {
        nums.remove(i);
    }
}
System.out.println(nums);

Answer: [3, 5]. The backward loop safely removes even numbers.

9. Common AP Mistakes and Debugging

Using length on ArrayLists

// Wrong
for (int i = 0; i < list.length; i++)
// Correct
for (int i = 0; i < list.size(); i++)

Using [] on ArrayLists

// Wrong
list[i]
// Correct
list.get(i)

Using size() on Arrays

// Wrong
arr.size()
// Correct
arr.length

2D Array Bounds

// Often wrong for non-square arrays
for (int c = 0; c < grid.length; c++)
// Safer
for (int c = 0; c < grid[r].length; c++)
Debug this: why does it skip values?
for (int i = 0; i < list.size(); i++) {
    if (list.get(i).equals("remove")) {
        list.remove(i);
    }
}

After removal, the next item shifts into the same index, but the loop increments i. That shifted item is skipped. Traverse backward or decrement i after removing.

10. AP-Style MCQ Practice

1. Which expression returns the number of elements in an ArrayList named items?

Answer: items.size()

2. Which expression returns the number of rows in int[][] data?

Answer: data.length

3. Which method replaces an ArrayList element without changing the list size?

Answer: set(index, obj)

4. Why is backward traversal often used when removing from an ArrayList?

Answer: It avoids skipping elements after removal shifts the remaining items left.

5. In grid[r][c], what does r represent?

Answer: The row index.

11. AP-Style FRQ Practice

FRQ A: Remove Slow Times

Write a method that removes all race times greater than cutoff from an ArrayList<Double>.

public static void removeSlowTimes(ArrayList<Double> times, double cutoff)
Show sample solution
public static void removeSlowTimes(ArrayList<Double> times, double cutoff) {
    for (int i = times.size() - 1; i >= 0; i--) {
        if (times.get(i) > cutoff) {
            times.remove(i);
        }
    }
}

FRQ B: Row Average

Write a method that returns the average of one row in a 2D integer array.

public static double rowAverage(int[][] data, int row)
Show sample solution
public static double rowAverage(int[][] data, int row) {
    int total = 0;
    for (int c = 0; c < data[row].length; c++) {
        total += data[row][c];
    }
    return (double) total / data[row].length;
}

FRQ C: Find Hottest Cell

Write a method that returns the largest value in a 2D array.

public static int maxValue(int[][] heat)
Show sample solution
public static int maxValue(int[][] heat) {
    int max = heat[0][0];
    for (int r = 0; r < heat.length; r++) {
        for (int c = 0; c < heat[r].length; c++) {
            if (heat[r][c] > max) {
                max = heat[r][c];
            }
        }
    }
    return max;
}

12. End-of-Unit Project: Heat Map and Performance Tracker

This project combines ArrayLists and 2D arrays in one applied program.

Part 1: Performance Tracker

Use an ArrayList<Double> to store race times. Add, remove, search, and filter times.

  • Add new times
  • Find fastest time
  • Remove times above a cutoff
  • Calculate average

Part 2: Heat Map Grid

Use a 2D array to model temperature readings across a room, field, or track surface.

  • Print the grid
  • Find the hottest cell
  • Find row averages
  • Find column averages

Part 3: Reflection

Explain why the race times used an ArrayList but the heat map used a 2D array. This is the key design thinking goal.

Starter Code

import java.util.ArrayList;

public class DataCollectionsProject {
    public static void main(String[] args) {
        ArrayList<Double> times = new ArrayList<Double>();
        times.add(12.4);
        times.add(11.9);
        times.add(13.1);
        times.add(11.7);

        int[][] heat = {
            {72, 74, 75, 73},
            {69, 70, 71, 72},
            {80, 82, 79, 78}
        };

        System.out.println("Fastest time: " + fastest(times));
        System.out.println("Hottest cell: " + maxValue(heat));
    }

    public static double fastest(ArrayList<Double> times) {
        double best = times.get(0);
        for (int i = 1; i < times.size(); i++) {
            if (times.get(i) < best) {
                best = times.get(i);
            }
        }
        return best;
    }

    public static int maxValue(int[][] grid) {
        int max = grid[0][0];
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] > max) {
                    max = grid[r][c];
                }
            }
        }
        return max;
    }
}