AP COMPUTER SCIENCE A • DATA COLLECTIONS

Introduction to Using Data Sets

Learn to store, traverse, and manipulate collections of data using arrays and ArrayLists in Java.

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
IBM's FORTRAN language introduced fixed-size arrays, giving programmers indexed access to contiguous memory blocks for numerical computation.
1972
C and Pointer-Based Arrays
The C language tied arrays directly to memory addresses, offering speed but requiring manual size management and bounds checking.
1995
Java's Array Type
Java introduced bounds-checked, zero-indexed arrays as first-class objects, eliminating many buffer-overflow errors common in C.
1998
Java Collections Framework
Java 2 shipped the Collections Framework, including ArrayList, giving developers resizable, type-safe lists built on top of arrays.
2004
Generics & Autoboxing
Java 5 added generics (ArrayList<String>) and autoboxing, making collections safer and more convenient for AP-level programming.

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.

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.

1

Indexed Access

Every element in an array or ArrayList occupies a numbered position starting at 0. You retrieve or modify any element in constant time using its index.
2

Fixed vs. Dynamic Size

An array's length is set at creation and cannot change. An ArrayList grows and shrinks automatically as elements are added or removed.
3

Traversal

Processing every element — computing a sum, finding a maximum, or filtering matches — requires a systematic walk through the collection, typically with a for or for-each loop.
4

Type Safety

Arrays store a declared type (primitives or objects). ArrayLists use generics (e.g., ArrayList<Integer>) and store only object references, relying on autoboxing for primitives.
KEY TAKEAWAY
Think of an array like a row of fixed mailboxes in an apartment lobby: the number of boxes is set when the building is constructed, and each box has a permanent number. An ArrayList is more like a growing filing cabinet — you can insert new folders or remove old ones, and the cabinet adjusts. Both let you locate any item instantly by its position, but they differ in flexibility and overhead.

Visual Explanation — Array vs. ArrayList

The top row shows a primitive 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.

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
int[] a = new int[n]; // size n, all zeros int[] b = {4, 8, 15, 16, 23}; // size 5, literal values String[] c = new String[3]; // size 3, all null
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
ArrayList<Type> list = new ArrayList<Type>(); list.add(element); // appends to end list.add(index, element); // inserts at index list.get(index); // returns element list.set(index, element); // replaces element list.remove(index); // removes & shifts list.size(); // current element count
The type parameter must be a reference type: use Integer instead of int. Java autoboxes primitives automatically.

Traversal Patterns

STANDARD FOR LOOP (ARRAY)
for (int i = 0; i < arr.length; i++) { // process arr[i] }
Use this when you need the index (e.g., to compare adjacent elements or to modify the array in place).
ENHANCED FOR-EACH LOOP
for (int val : arr) { // process val (read-only) }
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.

Common Data Set Operations

Six essential traversal algorithms applied to the same five-element integer array. The loop structure is identical in each case; only the body of the loop differs based on the operation.

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
When removing elements from an ArrayList inside a forward for loop, decrement i after each removal (or traverse backward) to avoid skipping the element that shifts into the vacated position.

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 SumTraverse 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 AverageDivide the sum by the number of elements. Use double 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.0
3
Step 3 — Build the Filtered ListCreate 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 CasesConsider 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 against scores.size() == 0 before dividing.
Add if (scores.size() == 0) return new ArrayList<>(); at the top of the method.

Array vs. ArrayList — Strengths & Limitations

Key differences tested on the AP Computer Science A exam
FeatureArrayArrayList
SizeFixed at creationGrows/shrinks dynamically
Primitive storageYes (int, double, boolean)No — must use wrapper classes (Integer, Double)
Access syntaxarr[i]list.get(i)
Modification syntaxarr[i] = vallist.set(i, val)
Insert/Remove in middleManual shifting requiredBuilt-in add(i, val) / remove(i)
Length query.length (field).size() (method)
PerformanceSlightly faster (no autoboxing)Small overhead from object wrapping
WHEN TO USE WHICH
Choose an array when the size of the data set is known in advance and will not change — for example, storing the RGB values of a single pixel (always 3 components). Choose an ArrayList when elements will be inserted or removed at runtime — for instance, maintaining a dynamic list of active users in a chat application. On the AP exam, if a method signature hands you an int[], work with array syntax; if it hands you an ArrayList<String>, use the ArrayList API.

Connection to Advanced Data Structures

How AP-level data set skills scale to college-level CS
AP-Level ConceptAdvanced Extension
1D array traversal2D arrays (matrices) — tested on the AP exam in FRQ #4
ArrayList<Type>LinkedList, HashMap, and other Collections Framework classes (post-AP)
Linear searchBinary search (requires sorted data) — O(log n) vs. O(n)
Selection / Insertion sortMerge 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.

Practice Problems

1
Which of the following statements about arrays and ArrayLists in Java is true? (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.
2
Consider the following code segment: 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
3
Consider the following code segment: 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]
PROBLEM 4APPLIED
Write a static method 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}.
PROBLEM 5CRITICAL THINKING
Write a static method 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.

Lesson 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.

Varsity Tutors • AP Computer Science A • Introduction to Using Data Sets