SECTION 1
Historical Context & Motivation
From the earliest days of computing, programs needed to operate on more than one piece of data at a time. Calculating a class average, sorting a roster alphabetically, or tallying votes in an election all require the program to hold many related values simultaneously. Storing each value in its own named variable quickly becomes impractical when the count grows to hundreds or thousands, so computer scientists developed data structures — organized containers that group related elements under a single name and provide efficient operations for access and modification.
1957 • FORTRAN Arrays
1972 • C and Pointer-Based Arrays
1995 • Java's Array Type
1998 • Java Collections Framework
2004 • Generics & Autoboxing
The central question this lesson addresses is straightforward yet foundational: how do we represent, access, and process collections of related data in Java? Mastering arrays and ArrayLists is essential for the AP Computer Science A exam, where roughly 30% of questions involve data collections, and three of the four free-response questions typically require traversal or manipulation of arrays or lists.
SECTION 2
Core Principles & Definitions
A data set in the context of AP Computer Science A is any structured collection of values that a program stores, traverses, and transforms. Java provides two primary vehicles for managing data sets at the AP level: the fixed-size array and the dynamically resizable ArrayList. Understanding when and why to choose one over the other is a core competency tested on the exam.
Indexed Access
0. You retrieve or modify any element in constant time using its index.Fixed vs. Dynamic Size
Traversal
for or for-each loop.Type Safety
ArrayList<Integer>) and store only object references, relying on autoboxing for primitives.KEY TAKEAWAY
SECTION 3
Visual Explanation — Array vs. ArrayList
int[] array with exactly 5 slots. The bottom row shows an ArrayList<Integer> that currently holds 5 elements but can grow via add() (dashed box). Both use zero-based indexing.In the diagram above, notice that both structures store the same data values at the same index positions. The critical difference is structural: the array's length field is immutable after construction, while the ArrayList maintains an internal array that it automatically replaces with a larger one when capacity is exceeded. For the AP exam, you should be comfortable declaring, initializing, and traversing both representations, as well as converting between them when a problem requires it.
SECTION 4
How It Works — Declaration, Initialization & Traversal
Array Declaration & Initialization
Java arrays are declared with a type followed by square brackets. You can initialize them with a size (all elements receive their default value — 0 for int, null for objects) or with an initializer list. The .length field (note: not a method) returns the array's size.
ARRAY CREATION PATTERNS
The variable n must be a non-negative integer. Accessing index < 0 or ≥ a.length throws ArrayIndexOutOfBoundsException.
ArrayList Declaration & Key Methods
ARRAYLIST CREATION & CORE METHODS
The type parameter must be a reference type: use Integer instead of int. Java autoboxes primitives automatically.
Traversal Patterns
STANDARD FOR LOOP (ARRAY)
Use this when you need the index (e.g., to compare adjacent elements or to modify the array in place).
ENHANCED FOR-EACH LOOP
The for-each loop works with both arrays and ArrayLists. It does not provide the index and should not be used to add or remove elements from an ArrayList during iteration.
SECTION 5
Common Data Set Operations
The diagram catalogs the six operations you will encounter most frequently on the AP exam. The accumulate pattern (sum, average) initializes a running total before the loop. The find extreme pattern (min or max) initializes a candidate to the first element and updates it whenever a better candidate is found. The count / filter pattern uses a conditional inside the loop to tally or collect elements meeting a criterion. The linear search terminates early when the target is found. Finally, the shift / remove pattern requires careful index management because removing an element from the middle of an array means shifting all subsequent elements left by one position.
AP Exam Pitfall
for loop, decrement i after each removal (or traverse backward) to avoid skipping the element that shifts into the vacated position.SECTION 6
Worked Example — Analyzing a Scores Data Set
Consider the following problem: given an ArrayList of Integer test scores, write a method that returns a new ArrayList containing only the scores that are above the class average.
Filter Above-Average Scores
- 1
Step 1 — Compute the Sum
Traverse the list with a for-each loop, accumulating the total. For the data set{72, 85, 90, 68, 95}, the sum is 72 + 85 + 90 + 68 + 95 = 410.int sum = 0; for (int s : scores) sum += s;→ sum = 410 - 2
Step 2 — Calculate the Average
Divide the sum by the number of elements. Usedoubledivision to preserve the fractional part: 410 / 5 = 82.0. Be careful:410 / 5in Java performs integer division unless at least one operand is a double.double avg = (double) sum / scores.size();→ avg = 82.0 - 3
Step 3 — Build the Filtered List
Create a new ArrayList<Integer>. Traverse the original list and add each score that exceeds the average. Scores 85, 90, and 95 are all greater than 82.0.ArrayList<Integer> result = new ArrayList<>(); for (int s : scores) { if (s > avg) result.add(s); } return result;→ [85, 90, 95] - 4
Step 4 — Verify Edge Cases
Consider what happens if the list is empty (division by zero) or if all scores are identical (no element exceeds the average, so the result is empty). Robust code should guard againstscores.size() == 0before dividing.Addif (scores.size() == 0) return new ArrayList<>();at the top of the method.
SECTION 7
Array vs. ArrayList — Strengths & Limitations
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed at creation | Grows/shrinks dynamically |
| Primitive storage | Yes (int, double, boolean) | No — must use wrapper classes (Integer, Double) |
| Access syntax | arr[i] | list.get(i) |
| Modification syntax | arr[i] = val | list.set(i, val) |
| Insert/Remove in middle | Manual shifting required | Built-in add(i, val) / remove(i) |
| Length query | .length (field) | .size() (method) |
| Performance | Slightly faster (no autoboxing) | Small overhead from object wrapping |
Key differences tested on the AP Computer Science A exam
WHEN TO USE WHICH
int[], work with array syntax; if it hands you an ArrayList<String>, use the ArrayList API.SECTION 8
Connection to Advanced Data Structures
| AP-Level Concept | Advanced Extension |
|---|---|
| 1D array traversal | 2D arrays (matrices) — tested on the AP exam in FRQ #4 |
| ArrayList<Type> | LinkedList, HashMap, and other Collections Framework classes (post-AP) |
| Linear search | Binary search (requires sorted data) — O(log n) vs. O(n) |
| Selection / Insertion sort | Merge sort, quicksort — O(n log n) divide-and-conquer algorithms |
| Wrapper classes (Integer) | Generics with bounded types, custom Comparable implementations |
How AP-level data set skills scale to college-level CS
The array and ArrayList patterns you master now form the algorithmic backbone of nearly every data structure you will encounter in a college data structures course. Two-dimensional arrays, which appear as the subject of FRQ #4 on every AP exam, are simply arrays of arrays — the same indexing and traversal logic applies, just with a nested loop. Sorting algorithms like selection sort and insertion sort operate on the same arrays you have been traversing, adding only the concept of swapping elements. Building fluency with one-dimensional data sets now will pay dividends throughout the rest of the course and the exam.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
- A. An array can store both primitive types and object references, while an ArrayList can only store primitive types.
- B. An ArrayList can change its size after construction, while an array cannot.
- C. The expression arr.length() returns the number of elements in an array arr.
- D. An ArrayList uses zero-based indexing, but a Java array uses one-based indexing.
Show answer (B)
length is a field, not a method, so the correct syntax is arr.length without parentheses. (D) is wrong because both arrays and ArrayLists use zero-based indexing.Question 2: BASIC CALCULATION
int[] data = {10, 20, 30, 40, 50};
int result = 0;
for (int i = 1; i < data.length; i += 2) {
result += data[i];
}
System.out.println(result);
What is printed?
(A) 90
(B) 60
(C) 150
(D) 50- A. 90
- B. 60
- C. 150
- D. 50
Show answer (B)
Question 3: INTERMEDIATE
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Diana");
for (int i = names.size() - 1; i >= 0; i--) {
if (names.get(i).length() <= 3) {
names.remove(i);
}
}
System.out.println(names);
What is printed?
(A) [Alice, Charlie, Diana]
(B) [Alice, Bob, Charlie, Diana]
(C) [Alice, Charlie]
(D) [Bob]- A. [Alice, Charlie, Diana]
- B. [Alice, Bob, Charlie, Diana]
- C. [Alice, Charlie]
- D. [Bob]
Show answer (A)
Question 4: APPLIED
4 ptspublic static double[] normalize(int[] data) that returns a new double[] of the same length where each element is the original value divided by the maximum value in data. You may assume data is non-empty and contains at least one positive value. For example, if data = {3, 6, 9}, the method returns {0.333..., 0.666..., 1.0}.Show answer
int max = data[0];
for (int val : data) {
if (val > max) max = val;
}
Point 2 — Create result array of correct size:
double[] result = new double[data.length];
Point 3 — Compute normalized values with double division: Each element must use floating-point division (cast numerator or denominator to double).
for (int i = 0; i < data.length; i++) {
result[i] = (double) data[i] / max;
}
Point 4 — Return the result array:
return result;Question 5: CRITICAL THINKING
3 ptspublic static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list) that returns a new ArrayList containing only the first occurrence of each value, preserving the original order. For example, if list = [3, 5, 3, 7, 5], the method returns [3, 5, 7]. Do not modify the original list.Show answer
ArrayList<Integer> result = new ArrayList<>();
for (int val : list) {
Point 2 — Check whether the value already exists in result before adding: Use !result.contains(val) or an equivalent manual search to determine uniqueness.
if (!result.contains(val)) {
result.add(val);
}
}
Point 3 — Return the new list (original list is unmodified):
return result;
Note: This approach runs in O(n²) because contains performs a linear scan for each element. A more efficient solution would use a HashSet, but that is beyond the AP subset.SUMMARY
Lesson Summary
Summary
This lesson introduced the foundational concepts for working with data sets in Java. An array provides fixed-size, zero-indexed storage for both primitives and objects, accessed via bracket notation (arr[i]) with the .length field reporting its size. An ArrayList offers dynamic resizing and a rich API including add(), get(), set(), remove(), and size(), but it requires wrapper classes for primitives.
The core traversal patterns — accumulating sums, finding extremes, counting matches, linear searching, and shifting elements — use the same loop structure with different body logic. The standard for loop is preferred when the index is needed; the enhanced for-each loop is cleaner for read-only traversals. When removing elements during iteration, traverse backward to avoid skipping. These patterns underpin nearly every data collections question on the AP Computer Science A exam.