Loading
Learn to store, traverse, and manipulate collections of data using arrays and ArrayLists in Java.
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.
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.
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.
0. You retrieve or modify any element in constant time using its index.for or for-each loop.ArrayList<Integer>) and store only object references, relying on autoboxing for primitives.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.
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.
n must be a non-negative integer. Accessing index < 0 or ≥ a.length throws ArrayIndexOutOfBoundsException.Integer instead of int. Java autoboxes primitives automatically.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.
for loop, decrement i after each removal (or traverse backward) to avoid skipping the element that shifts into the vacated position.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.
{72, 85, 90, 68, 95}, the sum is 72 + 85 + 90 + 68 + 95 = 410.int sum = 0; for (int s : scores) sum += s; → sum = 410double division to preserve the fractional part: 410 / 5 = 82.0. Be careful: 410 / 5 in Java performs integer division unless at least one operand is a double.double avg = (double) sum / scores.size(); → avg = 82.0ArrayList<Integer> result = new ArrayList<>();
for (int s : scores) {
if (s > avg) result.add(s);
}
return result; → [85, 90, 95]scores.size() == 0 before dividing.if (scores.size() == 0) return new ArrayList<>(); at the top of the method.| 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 |
int[], work with array syntax; if it hands you an ArrayList<String>, use the ArrayList API.| 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 |
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.
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) 50ArrayList<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]public 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}.public 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.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.
Keep learning with more lessons from the same subject.