AP CSA Unit 4: Data Collection - Complete Study Guide (2025)

AP Computer Science A – Unit 4: Data Collections (2025)

Unit 4 is all about working with collections of data. You’ll learn how to use arrays and ArrayLists, how to traverse them with loops, and how to implement classic AP Computer Science A algorithms like searching and sorting. This unit usually makes up 30–40% of the AP CSA exam, so it’s worth mastering.

 

 

📘 4.1 Unit Overview – Arrays & ArrayLists

In the AP CSA 2025 curriculum, Unit 4: Data Collections is where everything comes together: variables, methods, conditionals, and loops are now used to process multiple values at once.

By the end of this unit, you should be able to:

  • Declare, create, and initialize arrays
  • Use loops to traverse arrays and apply algorithms
  • Understand indexing, bounds, and off-by-one errors
  • Implement linear search and simple max/min patterns
  • Explain how basic sorting algorithms work conceptually
  • Use ArrayList<Type> and its key methods in Java
  • Predict how add, remove, and set affect positions and size
This page (Part 1) focuses on arrays. Part 2 will cover ArrayList, enhanced for loops, and a full Unit 4 quiz.

 

 

📦 4.2 What Is an Array?

An array is a fixed-size, ordered collection of elements of the same type. Arrays are great when you know:

  • How many items you need to store
  • That every item has the same type (e.g. all int, all double, all String)

Array Syntax in Java

// declaration and creation
int[] nums = new int[5];   // array of 5 ints, initially 0

// declaration + initialization
String[] names = {"Alex", "Jordan", "Sam"};

Arrays in Java are objects. The variable (nums, names) holds a reference to the actual array in memory.

int[] nums = new int[3]; nums ---> [ 0 ][ 0 ][ 0 ] 0 1 2 (indices)
Key idea: Array indices start at 0 and go up to length - 1. Accessing an index outside this range causes an ArrayIndexOutOfBoundsException.

 

 

🧱 4.3 Declaring, Creating, and Initializing Arrays

You’ll see three common steps with arrays: declare, create, and initialize.

1. Declare the Array Variable

int[] scores;

2. Create the Array (Allocate Memory)

scores = new int[4];   // space for 4 ints

3. Initialize the Elements

scores[0] = 90;
scores[1] = 82;
scores[2] = 100;
scores[3] = 75;

These steps can be combined:

int[] scores = {90, 82, 100, 75};

Default Values

  • int → 0
  • double → 0.0
  • boolean → false
  • Object references (like String) → null
On the AP CSA exam, you’re expected to know how arrays are constructed and how to index them correctly.

 

 

🎯 4.4 Indexing & Bounds – Avoiding Off-by-One Errors

Array indices run from 0 to length - 1. Using -1 or length as an index will crash your program.

Valid vs Invalid

int[] nums = {4, 7, 9, 2};
int len = nums.length;   // 4

// valid indices: 0,1,2,3
int first = nums[0];     // 4
int last  = nums[3];     // 2

// invalid:
// nums[-1];       // ❌ runtime error
// nums[4];        // ❌ runtime error

Typical Traversal Pattern

for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}
For loops that traverse arrays almost always use i = 0; i < array.length; i++. Watch for sneaky off-by-one mistakes on multiple choice questions.

 

 

🔁 4.5 Traversal Patterns – Sum, Count, Search

Most AP CSA array questions use a handful of very common loop patterns. If you master these, you’ll recognize them instantly on the exam.

1. Summing an Array

int sum = 0;
for (int i = 0; i < nums.length; i++) {
    sum += nums[i];
}

2. Counting Elements That Match a Condition

int countPositive = 0;
for (int i = 0; i < nums.length; i++) {
    if (nums[i] > 0) {
        countPositive++;
    }
}

3. Linear Search – Does Target Exist?

boolean found = false;
for (int i = 0; i < nums.length; i++) {
    if (nums[i] == target) {
        found = true;
        break;    // stop early once found
    }
}

4. Finding the Maximum

int max = nums[0];
for (int i = 1; i < nums.length; i++) {
    if (nums[i] > max) {
        max = nums[i];
    }
}
These patterns show up repeatedly in FRQs, especially in Unit 7/8 style questions that rely on traversing arrays or ArrayLists.

 

 

🏗 4.6 Nested Loops with Arrays

A nested loop is a loop inside another loop. This pattern is often used to:

  • Compare each element to every other element
  • Work with 2D-like structures
  • Generate tables or patterns

Compare All Pairs

for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
        System.out.println(nums[i] + " and " + nums[j]);
    }
}

This visits each pair of indices (i, j) with i < j.

2D-Style Traversal (Conceptual)

You don’t have to deeply master 2D arrays for AP CSA, but nested loops are often used for grid-like problems.

for (int row = 0; row < rows; row++) {
    for (int col = 0; col < cols; col++) {
        // process [row][col]
    }
}
Outer loop: controls rows Inner loop: controls columns Total iterations = rows × cols
On MCQs, a common question is: “How many times does this nested loop run?” Multiply the number of iterations from the outer loop and the inner loop.

 

 

🧮 4.7 Sorting Arrays – Conceptual Algorithms

AP CSA expects you to understand what sorting algorithms do, not necessarily to memorize every line of code. You should be able to:

  • Recognize that sorting rearranges elements into order (e.g., ascending)
  • Trace small sorting examples
  • Predict final array contents after a sorting process

Selection Sort (Conceptual)

  1. Find the smallest element in the unsorted part of the array
  2. Swap it with the element at the beginning of the unsorted part
  3. Repeat for the rest of the array
[ 7, 3, 5, 1 ] Pass 1: find smallest (1), swap with index 0 [ 1, 3, 5, 7 ] Pass 2: find smallest from index 1..end Already in order ... (done)

Bubble Sort (Conceptual)

Bubble sort repeatedly “bubbles up” larger elements by comparing neighbors and swapping them.

You might be asked to trace a few passes of a sort, but you won’t have to memorize the exact implementation.

 

 

🧵 4.8 Arrays of Strings and Other Objects

Arrays can store primitives (int, double, boolean) or object references (like String or your own classes).

String Array Example

String[] words = {"AP", "CSA", "is", "fun"};

for (int i = 0; i < words.length; i++) {
    System.out.println(words[i].toUpperCase());
}

Array of Custom Objects

Dog[] kennel = new Dog[3];
kennel[0] = new Dog("Max", 3);
kennel[1] = new Dog("Luna", 5);
kennel[2] = new Dog("Spot", 2);

for (int i = 0; i < kennel.length; i++) {
    kennel[i].bark();
}
Remember: when an array stores objects, each element is a reference. The array itself is an object that holds references to other objects.

 

 

⚠️ 4.9 Common Array Mistakes on the AP Exam

  • Using indices 1..length instead of 0..length-1
  • Forgetting to initialize elements before accessing them
  • Using <= array.length in loop conditions instead of <
  • Assuming arrays “resize themselves” like ArrayLists (they don’t!)
  • Mixing up length (array) vs length() (String)
  • Writing loops that never execute (condition false to start) or never end
  • Confusing primitive arrays vs object arrays (e.g., String[])
When you see array code on the exam, always check:
  1. Are indices starting at 0?
  2. Does the loop stop before array.length?
  3. Are all elements initialized before use?

 

 

🧪 4.10 Mini Practice – Trace These Arrays

Example 1 – Sum of Every Other Element

int[] data = {2, 4, 6, 8, 10};
int sum = 0;

for (int i = 0; i < data.length; i += 2) {
    sum += data[i];
}
System.out.println(sum);

Output: 18 (2 + 6 + 10)

Example 2 – Count Strings Longer Than 3

String[] arr = {"AP", "CSA", "Java", "Loops"};
int count = 0;

for (int i = 0; i < arr.length; i++) {
    if (arr[i].length() > 3) {
        count++;
    }
}
System.out.println(count);

Output: 2 (“Java” and “Loops”)

Example 3 – Reverse Print

int[] nums = {5, 9, 1};
for (int i = nums.length - 1; i >= 0; i--) {
    System.out.print(nums[i] + " ");
}

Output: 1 9 5

These small tracing exercises are exactly what AP CSA multiple-choice questions feel like. Practicing them regularly builds your speed and confidence.

 

 

 

 

 

 

📚 4.11 What Is an ArrayList?

An ArrayList<Type> is a resizable, ordered collection of objects. Unlike arrays, ArrayLists grow and shrink automatically. They store references to objects — never primitives.

To use ArrayList in Java, you must import it:

import java.util.ArrayList;

Create an ArrayList

ArrayList words = new ArrayList();

Java 7+ shortcut

ArrayList words = new ArrayList<>();
AP CSA always uses the ArrayList<Type> format, never raw types (e.g., not ArrayList).

 

 

🧰 4.12 Core ArrayList Methods You Must Master

The exam expects fluent use of these:

Method Description
add(obj) Adds to end
add(index, obj) Inserts at index, shifts elements right
get(index) Returns element at index
set(index, obj) Replaces element
remove(index) Removes, shifts elements left
size() Returns number of elements

Example

ArrayList list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

list.add(1, "X");     // [A, X, B, C]
list.remove(2);        // [A, X, C]
list.set(0, "Z");      // [Z, X, C]
Shifting behavior is critical. Removing shifts elements LEFT. Adding at an index shifts elements RIGHT.

 

 

🔁 4.13 Traversing ArrayLists

You can traverse an ArrayList using any of the following:

1. Index-Based Loop

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}
Use index-based loops when you need the index or when adding/removing elements.

2. Enhanced For Loop (For-Each)

for (String s : list) {
    System.out.println(s);
}

Cleaner, but has limitations:

  • ❌ cannot remove elements safely
  • ❌ cannot modify structure of the list
  • ❌ cannot access elements by index directly
AP CSA frequently tests what you can and cannot do with the enhanced for loop.

 

 

📦 4.14 Adding & Removing – Shifting Behavior

When you add(index, obj) or remove(index), elements shift positions. Understanding how elements move is essential for AP exam questions.

Example of Adding

ArrayList nums = new ArrayList<>();
nums.add(1);
nums.add(2);
nums.add(3);

nums.add(1, 9);
// result: [1, 9, 2, 3]

Example of Removing

nums.remove(2);
// removes value 2
// result: [1, 9, 3]
Index: 0 1 2 3 Before: [A, B, C, D] remove(1) After: [A, C, D] Shift: C->1, D->2
Many AP questions deliberately test your understanding of shifting. Always visualize how indices change after a removal.

 

 

🔍 4.15 Searching & Filtering ArrayLists

Searching an ArrayList works exactly like searching an array—just replace array[i] with list.get(i).

Linear Search

boolean found = false;

for (int i = 0; i < list.size(); i++) {
    if (list.get(i).equals(target)) {
        found = true;
        break;
    }
}

Counting Matches

int count = 0;

for (String s : list) {
    if (s.length() > 3) {
        count++;
    }
}
AP loves “count the number of elements that match a rule” questions.

 

 

⚠️ 4.16 Removing While Traversing

Removing elements inside a traversal loop is tricky because removal shifts elements.

Incorrect (skips elements!)

for (int i = 0; i < list.size(); i++) {
    if (list.get(i) < 0) {
        list.remove(i);  // ❌ shifts left, next element skipped
    }
}

Correct Approaches

Approach 1: Traverse Backward

for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i) < 0) {
        list.remove(i);
    }
}

Approach 2: Decrement i after removal

for (int i = 0; i < list.size(); i++) {
    if (list.get(i) < 0) {
        list.remove(i);
        i--;   // stay at same index
    }
}
The AP exam frequently tests your ability to remove elements correctly.

 

 

🧪 4.17 FRQ-Style ArrayList Examples

Example 1 – Remove All Odd Numbers

public void removeOdds(ArrayList nums) {
    for (int i = nums.size() - 1; i >= 0; i--) {
        if (nums.get(i) % 2 != 0) {
            nums.remove(i);
        }
    }
}

Example 2 – Build a List of Long Strings

public ArrayList longStrings(String[] arr) {
    ArrayList res = new ArrayList<>();

    for (String s : arr) {
        if (s.length() > 5) {
            res.add(s);
        }
    }
    return res;
}

Example 3 – Replace All Negative Values with Zero

public void fixNegatives(ArrayList nums) {
    for (int i = 0; i < nums.size(); i++) {
        if (nums.get(i) < 0) {
            nums.set(i, 0);
        }
    }
}
These patterns appear constantly in FRQs involving arrays and ArrayLists.

 

 

📝 Unit 4 Quiz – Arrays & ArrayLists (10 Questions)

Question 1

What does size() return for an ArrayList?

  • A. the number of indices
  • B. the number of elements
  • C. the capacity
  • D. the last index

Question 2

Which loop should you avoid modifying an ArrayList inside?

  • A. for-each loop
  • B. while loop
  • C. backward for loop
  • D. index-based loop with i--

Question 3

ArrayLists can store:

  • A. only primitives
  • B. only Strings
  • C. only objects
  • D. any type

Question 4

What happens when you call remove(0)?

  • A. removes the first element and shifts left
  • B. removes the last element
  • C. clears the list
  • D. throws an error

Question 5

What is printed?

ArrayList a = new ArrayList<>();
a.add(1);
a.add(2);
a.add(3);
a.remove(1);
System.out.println(a);
  • A. [1, 2, 3]
  • B. [1, 3]
  • C. [2, 3]
  • D. [3, 1]

Question 6

What is required when creating an ArrayList?

  • A. import java.util.ArrayList;
  • B. defining capacity
  • C. specifying primitive type
  • D. a constructor with parameters

Question 7

Which method replaces an item at a given index?

  • A. add()
  • B. get()
  • C. set()
  • D. remove()

Question 8

Which is a valid enhanced for loop?

ArrayList list;
  • A. for (int i : list)
  • B. for (String s : list)
  • C. for (list item : String)
  • D. for (int i = 0 : list)

Question 9

What does add(index, value) do?

  • A. replaces the value at index
  • B. inserts and shifts right
  • C. removes the value at index
  • D. appends to the end

Question 10

Which loop is safest for removing elements?

  • A. for-each loop
  • B. forward loop without adjustment
  • C. backward for loop
  • D. while loop with i++ always

 

 

🚀 Next Steps

You’ve now completed the largest and most important AP CSA unit — Data Collections. The next unit (Unit 5) transitions into writing more complex methods that use arrays, ArrayLists, and control structures together.

Add your internal navigation link here:
Continue to AP CSA Exam Review Strategies →

Contact form