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, andsetaffect positions and size
📦 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, alldouble, allString)
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.
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
🎯 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]);
}
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];
}
}
🏗 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]
}
}
🧮 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)
- Find the smallest element in the unsorted part of the array
- Swap it with the element at the beginning of the unsorted part
- Repeat for the rest of the array
Bubble Sort (Conceptual)
Bubble sort repeatedly “bubbles up” larger elements by comparing neighbors and swapping them.
🧵 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();
}
⚠️ 4.9 Common Array Mistakes on the AP Exam
- Using indices
1..lengthinstead of0..length-1 - Forgetting to initialize elements before accessing them
- Using
<= array.lengthin loop conditions instead of< - Assuming arrays “resize themselves” like ArrayLists (they don’t!)
- Mixing up
length(array) vslength()(String) - Writing loops that never execute (condition false to start) or never end
- Confusing primitive arrays vs object arrays (e.g.,
String[])
- Are indices starting at 0?
- Does the loop stop before
array.length? - 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
📚 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
ArrayListwords = new ArrayList ();
Java 7+ shortcut
ArrayListwords = new ArrayList<>();
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
ArrayListlist = 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]
🔁 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));
}
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
📦 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
ArrayListnums = 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]
🔍 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++;
}
}
⚠️ 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
}
}
🧪 4.17 FRQ-Style ArrayList Examples
Example 1 – Remove All Odd Numbers
public void removeOdds(ArrayListnums) { 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 ArrayListlongStrings(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(ArrayListnums) { for (int i = 0; i < nums.size(); i++) { if (nums.get(i) < 0) { nums.set(i, 0); } } }
📝 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
Answer: B
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--
Answer: A
Question 3
ArrayLists can store:
- A. only primitives
- B. only Strings
- C. only objects
- D. any type
Answer: C
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
Answer: A
Question 5
What is printed?
ArrayLista = 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]
Answer: B
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
Answer: A
Question 7
Which method replaces an item at a given index?
- A. add()
- B. get()
- C. set()
- D. remove()
Answer: C
Question 8
Which is a valid enhanced for loop?
ArrayListlist;
- A. for (int i : list)
- B. for (String s : list)
- C. for (list item : String)
- D. for (int i = 0 : list)
Answer: B
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
Answer: B
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
Answer: C
🚀 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 →