| Learning Objective | Essential Knowledge |
|---|---|
4.1.A |
|
4.1.B |
|
4.1.C |
|
Data Collections
AP Computer Science A · Topic 4
13:32
Data Collections
Take one photo on your phone. To the computer it is not a picture at all — it is a grid of numbers, one for every pixel, about twelve million of them. Now try…
English narration · English + 中文 subtitles burned in
4.1
The Ethics of Collecting Data
Syllabus
Source: College Board AP Course and Exam Description

Programs that gather data raise questions of privacy 隐私 and consent 同意. Collect only what is needed, protect it, and be honest about its use. Data can carry bias 偏见 if it does not represent everyone fairly, leading to unfair results – a responsibility that comes with storing information.
| English |
|---|
| privacy/ˈprɪvəsi/ |
| consent/kənˈsent/ |
| bias/ˈbaɪəs/ |
4.2
Why We Need Data Structures
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.2.A |
|
Source: College Board AP Course and Exam Description

A single variable 变量 holds one value; real problems need to store many related values – a class roster, pixels, sensor readings. A data structure 数据结构 organizes a collection so we can store, find, and process items efficiently. The AP course uses three: the array, the ArrayList, and the 2D array.
| English |
|---|
| variable/ˈveərɪəbl/ |
| data structure/ˈdeɪtə ˈstrʌktʃə/ |
4.3
Making and Reading an Array
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.3.A |
|
Source: College Board AP Course and Exam Description
An array 数组 is a fixed-size, ordered collection of same-type values. Indices 索引 run from 0 to length - 1:

int[] nums = new int[5]; // five zeros
int[] vals = {3, 1, 4, 1, 5}; // initialized
int first = vals[0]; // 3
int n = vals.length; // 5 (a field, not a method)
Accessing an index outside 0..length-1 throws an ArrayIndexOutOfBoundsException.
Worked example. For int[] vals = {3, 1, 4, 1, 5};:
| Expression | Value |
|---|---|
vals[2] |
4 |
vals[vals.length - 1] |
5, the last element |
vals[1] + vals[3] |
2 |
vals[vals.length] |
vals[5]: throws the exception |
new int[5] fills the array with 0; new double[5] with 0.0, new boolean[5] with false and new String[5] with null. An array's size cannot change once it is made.
| English |
|---|
| array/əˈreɪ/ |
| index/ˈɪndeks/ |
4.4
Visiting Every Element of an Array
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.4.A |
|
Source: College Board AP Course and Exam Description
Traverse 遍历 an array with a for loop (gives the index) or an enhanced for / for-each loop (gives each value, read-only):
for (int i = 0; i < a.length; i++) { a[i] *= 2; } // can modify
for (int v : a) { System.out.println(v); } // read each value

Common mistake. An enhanced for loop gives a copy of each value, so this changes nothing in the array:
int[] a = {1, 2, 3};
for (int v : a) {
v *= 2; // doubles the copy v only
}
// a is still {1, 2, 3}
To change the elements, use the index loop: a[i] *= 2;. Use an index loop also when the position matters, such as comparing a[i] with a[i + 1]; then stop at i < a.length - 1.
| English |
|---|
| Traverse/trəˈvɜːs/ |
4.5
Standard Array Algorithms
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.5.A |
|
Source: College Board AP Course and Exam Description
Master these patterns: compute a sum or average, find the max/min, count items meeting a condition, check for a duplicate 重复项, and reverse or shift elements 元素. Each is a traversal with a running result:
int sum = 0;
for (int v : a) sum += v;
double avg = (double) sum / a.length;

Worked example. Reverse an array in place by swapping from both ends.
for (int i = 0; i < a.length / 2; i++) {
int temp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = temp;
}
i |
swaps | a after |
|---|---|---|
| start | {3, 1, 4, 1, 5} |
|
| 0 | a[0] and a[4] |
{5, 1, 4, 1, 3} |
| 1 | a[1] and a[3] |
{5, 1, 4, 1, 3} |
a.length / 2 is 2, so the middle element stays put. Looping to a.length would swap every pair twice and put the array back as it was. A swap needs temp: a[i] = a[j]; a[j] = a[i]; loses the old a[i].
| English |
|---|
| duplicate |
| element/ˈelɪmənt/ |
4.6
Reading Data from a Text File
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.6.A |
|
Source: College Board AP Course and Exam Description
File and IOException live in java.io, so a program that reads a file needs import java.io.*; as well as import java.util.Scanner; for the Scanner. Opening a file can fail (it might not exist), and Java forces you to handle that – the simplest way is to add throws IOException to the method header 方法头. A Scanner then reads the file line by line, using hasNext... to test before reading:
import java.io.*;
import java.util.Scanner;
...
public static void readFile() throws IOException {
Scanner f = new Scanner(new File("data.txt"));
while (f.hasNextLine()) {
String line = f.nextLine();
}
}
Reading typed tokens 标记 with nextInt(), nextDouble(), or nextBoolean() throws an InputMismatchException if the next token is the wrong type – for example calling nextInt() when the next thing in the file is the word cat.
| English |
|---|
| method header |
| token |
4.7
Wrapping a Number in an Object
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.7.A |
|
Source: College Board AP Course and Exam Description
An ArrayList stores objects 对象, not primitives 基本类型, so a primitive is wrapped in an object: Integer wraps int, Double wraps double. Java does this with autoboxing 自动装箱 (int to Integer) and unboxing 自动拆箱 (back again) automatically, so you can write list.add(5) and int x = list.get(0).

| English |
|---|
| object/ˈɒbdʒekt/ |
| primitive/ˈprɪmɪtɪv/ |
| autoboxing/ˌɔːtəʊˈbɒksɪŋ/ |
| unboxing/ʌnˈbɒksɪŋ/ |
4.8
The ArrayList Toolbox
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.8.A |
|
Source: College Board AP Course and Exam Description
An ArrayList 动态数组 grows and shrinks as you add or remove items. Declare it with the element type in <>:
ArrayList<String> names = new ArrayList<String>();
names.add("Amy"); // append
names.add(0, "Bob"); // insert at index
names.get(0); // read
names.set(1, "Cara"); // replace
names.remove(0); // delete, shifts the rest left
names.size(); // count (a method, unlike array.length)
Worked example. The list after each call above:
| Call | names |
Returns |
|---|---|---|
add("Amy") |
[Amy] |
true |
add(0, "Bob") |
[Bob, Amy] |
nothing |
get(0) |
[Bob, Amy] |
"Bob" |
set(1, "Cara") |
[Bob, Cara] |
"Amy", the old value |
remove(0) |
[Cara] |
"Bob", the removed value |
size() |
[Cara] |
1 |
Indexes must be from 0 to size() - 1, except that add(index, x) also accepts size(), adding at the end; any other index throws an IndexOutOfBoundsException.
| English |
|---|
| ArrayList/əˈreɪ lɪst/ |
4.9
Visiting Every Element of an ArrayList
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.9.A |
|
Source: College Board AP Course and Exam Description
Traverse with an index loop or a for-each loop, just like arrays (use size() and get(i)):
for (int i = 0; i < list.size(); i++) { ... list.get(i) ... }
for (String s : list) { ... }
Exam skill: when removing items in an index loop, either loop backwards or do not increment i after a removal – otherwise removing shifts elements left and you skip one. And never add or remove elements while traversing an ArrayList with a for-each loop: changing its size mid-loop throws a ConcurrentModificationException, so use an index loop (backwards, as above) whenever you must remove.
4.10
Standard ArrayList Algorithms
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.10.A |
|
Source: College Board AP Course and Exam Description
The same algorithms 算法 as arrays – max/min, count, sum – plus insertion and deletion that arrays cannot do easily. A common task is to remove all elements matching a condition, handling the index-shift carefully.
Worked example. Remove every even number from nums, which holds [2, 4, 5, 6].
A forward loop with i++ after every pass goes wrong:
i |
nums.get(i) |
action | nums after |
|---|---|---|---|
| 0 | 2 | remove | [4, 5, 6] |
| 1 | 5 | keep | [4, 5, 6] |
| 2 | 6 | remove | [4, 5] |
The 4 slid into index 0 after the first removal and was never checked. Looping backwards avoids this, because removing shifts only elements already checked:
for (int i = nums.size() - 1; i >= 0; i--) {
if (nums.get(i) % 2 == 0) {
nums.remove(i);
}
}
This leaves [5].
| English |
|---|
| algorithm/ˈælɡərɪθəm/ |
4.11
Grids: Two-Dimensional Arrays
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.11.A |
|
Source: College Board AP Course and Exam Description
A 2D array 二维数组 is a grid (rows and columns) – an array of arrays:

int[][] grid = new int[3][4]; // 3 rows, 4 columns
grid[r][c] = 7; // row r, column c
int rows = grid.length; // 3
int cols = grid[0].length; // 4
![A Java 2D array: grid[row][col], with both indexes starting at 0](/handout-media/ap_computer_science_a/assets/04-array-2d-java.png?v=1792758393)
Index a 2D array by row and column
A 2D array is a grid addressed by [row][col]. Move the indices and watch which cell they select — row first, then column, both counting from 0.
| English |
|---|
| 2D array/ˌtuː ˈdiː əˈreɪ/ |
4.12
Walking Through a Grid
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.12.A |
|
Source: College Board AP Course and Exam Description
Visit every cell with nested loops 嵌套循环 – the outer over rows, the inner over columns (row-major order 行主序):
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++)
System.out.print(grid[r][c]);
To go column by column (column-major order), swap the loops: the outer over c < grid[0].length, the inner over r < grid.length, still writing grid[r][c]. A common mistake is to use grid.length as the column limit: in a 3 × 4 grid that skips column 3, and in a 4 × 3 grid it throws an ArrayIndexOutOfBoundsException.
| English |
|---|
| nested loop/ˈnestɪd luːp/ |
| row-major order/rəʊ ˈmeɪdʒə ˈɔːdə/ |
4.13
Standard 2D Array Algorithms
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.13.A |
|
Source: College Board AP Course and Exam Description
Typical grid tasks: sum a row or column, find the max in the grid, count matching cells, or sum a diagonal (where r == c). Each is a nested traversal with a running result.

Worked example. Find the sum of each column of
int[][] m = { {1, 2, 3},
{4, 5, 6} };
for (int c = 0; c < m[0].length; c++) {
int colSum = 0; // reset for each column
for (int r = 0; r < m.length; r++) {
colSum += m[r][c];
}
System.out.print(colSum + " ");
}
The outer loop picks a column, the inner loop goes down it: $1 + 4 = 5$, $2 + 5 = 7$, $3 + 6 = 9$, so the output is 5 7 9. colSum is set to 0 inside the outer loop; declared before both loops, it would print the running totals 5 12 21. The main diagonal of a square grid needs only one loop: sum += g[i][i];.
4.14
Finding a Value: Linear and Binary Search
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.14.A |
|
Source: College Board AP Course and Exam Description
- Linear search 线性搜索 checks each element in turn – works on any list, taking up to $n$ steps.
- Binary search 二分搜索 works only on a sorted 已排序 list: check the middle, then discard the half that cannot contain the target, repeating. It takes about $\log_2 n$ steps – far faster on large data.


int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
Exam skill: binary search requires sorted data; know how many comparisons it makes and how lo, hi, mid update.
Worked example. Search for target = 40 in the sorted array {3, 9, 14, 23, 31, 42, 55} (indices 0–6). Start lo=0, hi=6:
mid = (0+6)/2 = 3,a[3]=23 < 40, solo = 4;mid = (4+6)/2 = 5,a[5]=42 > 40, sohi = 4;mid = (4+4)/2 = 4,a[4]=31 < 40, solo = 5;- now
lo (5) > hi (4), so the loop ends –40is not present.
Each step halved the range, so even this miss took only three comparisons.
Compare linear and binary search
Linear search checks every element in turn; binary search halves a sorted list each step. Watch binary search reach the target in far fewer comparisons.
| English |
|---|
| Linear search/ˈlɪnɪə sɜːtʃ/ |
| Binary search/ˈbaɪnəri sɜːtʃ/ |
| sorted/ˈsɔːtɪd/ |
4.15
Putting Data in Order: Selection and Insertion Sort
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.15.A |
|
Source: College Board AP Course and Exam Description
- Selection sort 选择排序 repeatedly finds the smallest remaining element and swaps it into place.
- Insertion sort 插入排序 grows a sorted front, inserting each new element where it belongs.

Both are simple and take about $n^2$ steps on average – fine for small arrays. Be able to trace the array after each pass.
Watch a sorting algorithm order a list
A sort rearranges elements into order. Step through selection/insertion sort to see the sorted region grow one element at a time.
| English |
|---|
| Selection sort/sɪˈlekʃn sɔːt/ |
| Insertion sort/ɪnˈsɜːʃn sɔːt/ |
4.16
Methods That Call Themselves: Recursion
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.16.A |
|
Source: College Board AP Course and Exam Description
Recursion 递归 is a method that calls itself on a smaller input. It needs a base case 基本情况 that stops the calls, and a recursive case 递归情形 that moves toward the base:
public static int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
Deep recursion without a reachable base case can cause a stack overflow 栈溢出.
Recursion and iteration are interchangeable. Any recursive solution can be rewritten with a loop (an iterative 迭代的 approach), and any loop can be rewritten with recursion - they solve the same problems. The factorial above is identical in effect to an iterative version:
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) result *= i; // same answer, no self-call
return result;
}
So the choice is about clarity, not capability: recursion reads naturally for problems with a self-similar structure (trees, merge sort), while iteration avoids the memory cost of stacking a call frame per step. The exam may ask you to convert one into the other.
Unfold a recursive call
A recursive method calls itself on a smaller input until it hits a base case, then the results fold back up. Step through to watch the calls stack and unwind.
| English |
|---|
| Recursion/rɪˈkɜːʃn/ |
| base case/beɪs keɪs/ |
| recursive case/rɪˈkɜːsɪv keɪs/ |
| stack overflow/stæk ˌəʊvəˈfləʊ/ |
| iterative/ˈɪtərətɪv/ |
4.17
Recursive Search and Merge Sort
Syllabus
| Learning Objective | Essential Knowledge |
|---|---|
4.17.A |
|
4.17.B |
|
4.17.C |
|
Source: College Board AP Course and Exam Description
Recursion powers efficient algorithms. Binary search can be written recursively (search the correct half). Merge sort 归并排序 splits the array in half, sorts each half recursively, then merges the two sorted halves – taking about $n\log_2 n$ steps, much faster than selection or insertion sort on large data.

Worked example. Trace factorial(4). Each call defers to a smaller one: factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1). factorial(1) hits the base case and returns 1, so the calls unwind inward: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 6 = 24. Writing each call above its returned value is the reliable way to trace recursion.
Exam skill: trace a recursive method by writing out each call and its return value, and know that merge sort's efficiency ($n\log n$) beats the $n^2$ simple sorts.
| English |
|---|
| Merge sort/mɜːdʒ sɔːt/ |
4.17
Exam tips
- Weigh both benefits and harms of collecting data — this unit is tested through short written justification, not code.
- Protect personally identifiable information (PII) 个人身份信息 and explain privacy and security risks in context.
- Name real harms: data breaches, surveillance, and algorithmic bias from unrepresentative data.
- Respect intellectual property and licensing when you reuse code or data.
- Give a specific, reasoned answer — a vague "it could be bad" earns no marks.
| English |
|---|
| personally identifiable information/ˈpɜːsənəli aɪˈdentɪfaɪəbl ˌɪnfəˈmeɪʃn/ |
Interactive lessons on this topic
Work through it step by step, with instant-check exercises.
- Ethics of Data Collection
- Introduction to Data Sets
- Array Creation and Access
- Array Traversals
- Implementing Array Algorithms
- Using Text Files
- Wrapper Classes
- ArrayList Methods
- ArrayList Traversals
- Implementing ArrayList Algorithms
- 2D Array Creation and Access
- 2D Array Traversals
- Implementing 2D Array Algorithms
- Searching Algorithms
- Sorting Algorithms
- Recursion
- Recursive Searching and Sorting