Why it matters. In 2006 Netflix released 100 million film ratings from about 480,000 customers for a public prize competition, with names replaced by numbers. Two researchers at the University of Texas, Arvind Narayanan and Vitaly Shmatikov, showed in 2008 that many of those “anonymous” customers could be identified by matching a few of their ratings and dates with public reviews on IMDb. A planned second competition was cancelled after a privacy lawsuit. Data structures make it easy to collect and search huge amounts of data - this unit teaches both how to do it and why to think before you do.
Server racks in a data centre — large collections of data raise ethical questions about collection and use
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.
Protecting privacy. Personal data stored by a program can be leaked in a data breach, sold, or combined with other data to identify a person, as in the Netflix case. When you design a program:
collect only the data the program really needs;
ask for the user's consent, and say how the data will be used;
store passwords and personal details securely, and delete data that is no longer needed.
Data quality and algorithmic bias.Algorithmic bias is a systemic, repeated error in a program that gives unfair results to one group of users. It often comes from the data set, not from a coding mistake:
how the data was collected — an online survey only reaches people who are online; data from one city may not describe a whole country. Check the collection method before you draw conclusions from the data.
incomplete data — missing values (for example a blank age) can make averages wrong or crash a program that expects a number.
inaccurate data — typing errors or old records give wrong results, however correct the code is.
Worked example. A company trains a program to sort job applications, using the records of people it hired over the last ten years. Most of those people were men. Explain how this could cause algorithmic bias and suggest one way to reduce it. The program learns that features common in past hires predict success, so it scores applications from women lower — a repeated, unfair outcome for one group, even though no line of code mentions gender. To reduce it: check the data set for groups that are under-represented before using it, test the program's results separately for each group, and remove features that stand in for the group (such as membership of a women's club).
A filing cabinet: collections store many values under one name so algorithms can process them
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.
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)
A one-dimensional array (a list) with its indices and bounds
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.
4.4.A.3 增强型 for 循环头包含一个变量,称为增强型 for 循环变量。在增强型 for 循环的每次迭代中,增强型 for 循环变量被赋值为元素的副本,而无需使用其索引。
4.4.A.4 为增强型 for 循环变量赋予新值不会改变存储在数组中的值。
4.4.A.5 当数组存储对象引用时,可以通过调用增强型 for 循环变量上的方法来修改属性。这不会改变存储在数组中的对象引用。
4.4.A.6 使用增强型 for 循环编写的用于遍历数组元素的代码可以重写为使用索引 for 循环或 while 循环。
来源:College Board AP 课程与考试说明
English
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
Traversing an array with an indexed for loop or an enhanced for loop
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.
Master these patterns: compute a sum or average, find the max/min, count items meeting a condition, check for a duplicate 重复项, and reverse or shiftelements 元素. Each is a traversal with a running result:
int sum = 0;
for (int v : a) sum += v;
double avg = (double) sum / a.length;
Finding the maximum of an array, traced pass by pass
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].
Worked example: is there a duplicate? Write a method that returns true if any value appears more than once in an int array. Compare every element with every element after it, using a nested loop; return true as soon as a pair matches, and false only after every pair has been checked.
public static boolean hasDuplicate(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
return true;
}
}
}
return false;
}
For {3, 1, 4, 1, 5} the pairs checked are (3,1), (3,4), (3,1), (3,5), then (1,4), (1,1): a match, so the method returns true. Starting j at i + 1 matters: starting at 0 would compare a[0] with itself and always return true. Putting return false; inside the loop, in an else, is a common error: the method would stop after the first pair.
排除说明: 在同一输入源上编写或分析同时使用 nextLine 和其他 Scanner 方法的代码不在 AP 计算机科学 A 课程和考试范围内。
4.6.A.8 以下额外的 String 方法(包括其功能和使用场景)属于 Java 快速参考表:
String[] split(String del) 返回一个 String 数组,其中每个元素都是 this String 的子串,该字符串围绕给定表达式 del 的匹配项进行了分割。
排除说明: 参数 del 使用的格式称为正则表达式。编写或分析使用任何正则表达式特殊属性(例如 \\*、\\.)的代码不在 AP 计算机科学 A 课程和考试范围内。
4.6.A.9 可以使用 while 循环配合 hasNext 方法作为循环条件,以检测文件中是否仍包含可读元素。
4.6.A.10 当程序不再使用文件时,应将其关闭。通过调用 Scanner 中的 close 方法来关闭文件。
来源:College Board AP 课程与考试说明
English
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.
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).
boolean add(E obj) appends obj to end of list; returns true.
void add(int index, E obj) 插入 obj 在位置 index(0 <= index <= size),将位置 index 及更高位置的元素向右移动(其索引增加 1 ),并将大小增加 1 。
E get(int index) 返回列表中位置 index 处的元素。
E set(int index, E obj) 将位置 index 处的元素替换为 obj;返回原来位于位置 index 的元素。
E remove(int index) 移除位置 index 处的元素,将位置 index + 1 及更高位置的元素向左移动(其索引减 1),并将大小减 1;返回原来位于位置 index 的元素。
4.8.A.6ArrayList 的索引从 0 开始,到元素总数 - 1 结束。
来源:College Board AP 课程与考试说明
English
What an ArrayList really is
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.
4.9.A.4 在使用增强 for 循环遍历 ArrayList 的同时改变其大小可能会导致 ConcurrentModificationException(并发修改异常)。因此,当使用增强 for 循环遍历 ArrayList 时,不应添加或删除元素。
来源:College Board AP 课程与考试说明
English
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.
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);
}
}
4.12.A.1 嵌套迭代语句用于遍历和访问二维数组中的所有或有序序列的元素。由于二维数组被存储为数组的数组,因此使用 for 循环和增强型 for 循环遍历二维数组的方式与一维数组对象类似。可以编写嵌套迭代语句以按行优先顺序、列优先顺序或唯一定义的顺序遍历二维数组。行优先顺序指的是遍历沿每一行进行的二维数组元素排序方式,而列优先顺序遍历则是沿每一列向下进行。
4.12.A.2 用于遍历二维数组的嵌套增强型 for 循环的外层循环遍历的是行。因此,外层增强型 for 循环变量必须是每一行的类型,即一维数组。内层循环遍历单行。因此,内层增强型 for 循环变量必须与存储在一维数组中的元素类型相同。将新值赋给增强型 for 循环变量不会改变数组中存储的值。
来源:College Board AP 课程与考试说明
English
Traversing a 2-D array
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.
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.
Row-major and column-major traversal of a 2D array
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];.
Binary search: halve and conquerA card catalogue: because the cards are sorted, you can halve the search again and again, as binary search does
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.
Linear search checks each element in turn: the target at index 5 takes 6 comparisonsBinary search halves the range at each step
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, so lo = 4;
mid = (4+6)/2 = 5, a[5]=42 > 40, so hi = 4;
mid = (4+4)/2 = 4, a[4]=31 < 40, so lo = 5;
now lo (5) > hi (4), so the loop ends – 40 is not present.
Each step halved the range, so even this miss took only three comparisons.
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.
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.
Merge sort splits the array to single elements, then merges sorted halves back up
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.
Weigh both benefits and harms of collecting data for multiple-choice questions. The free-response section requires Java code, including ArrayList and 2D-array algorithms.
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.
For a data-quality question, say how the data was collected, and whether it is incomplete or inaccurate, and link that to the wrong or unfair result.
To check for duplicates, compare each element with every later one (j = i + 1); return false only after both loops finish.
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.
Common mistakes (whole unit).
Mixing up the three “sizes”: arr.length (array, no brackets), str.length() (String), list.size() (ArrayList).
Removing from an ArrayList while looping forwards with an index, which skips the element after each removal. Loop backwards, or only increase the index when nothing is removed.
Trying to change array elements through an enhanced for loop variable.
Running binary search on unsorted data.
Writing a recursive method with no base case, or one that the recursive calls never reach.
Practice.
For int[] a = {5, 2, 8, 1};, what is a[a.length - 1], and what happens with a[4]?
list holds [10, 20, 30]. After list.add(1, 15); and then list.remove(0);, what does list hold?
What is the greatest number of elements binary search examines in a sorted array of 16 elements?
Write a method public static int max(int[] arr) that returns the largest value in a non-empty array.
After int[][] g = new int[3][4];, what are g.length and g[0].length?
public static int mystery(int n) { if (n <= 1) return 1; return n + mystery(n - 2); } What is mystery(7)?
A school app collects students' locations to track attendance. Give one benefit, one risk, and one way to reduce the risk.
Answers.
1; a[4] throws an ArrayIndexOutOfBoundsException (valid indices are 0 to 3).
[15, 20, 30].
5 ($16 \to 8 \to 4 \to 2 \to 1$: at most $\log_2 16 + 1$ checks).
One answer:
public static int max(int[] arr) {
int best = arr[0];
for (int v : arr) {
if (v > best) {
best = v;
}
}
return best;
}
3 (rows) and 4 (columns).
$7 + 5 + 3 + 1 = 16$.
Example: benefit - accurate, automatic attendance; risk - a data breach could reveal where students are; reduction - collect location only on school grounds during school hours, and delete it after attendance is recorded.