Skip to content
Mar 1

AP Computer Science A: Array and ArrayList FRQs

MT
Mindli Team

AI-Generated Content

AP Computer Science A: Array and ArrayList FRQs

Mastering array and ArrayList manipulation is non-negotiable for success on the AP Computer Science A exam, especially since Free Response Question 3 consistently tests these skills. Your ability to traverse, modify, and reason about these collections directly impacts your score on a question that typically carries significant weight. This guide breaks down the exact techniques you need, from foundational loops to advanced problem-solving strategies, ensuring you can approach any FRQ with confidence.

Understanding Arrays and ArrayLists

At their core, both arrays and ArrayLists are data structures that store ordered collections of elements. However, their implementations and capabilities differ crucially. An array is a fixed-size, indexed container that can hold either primitive types (like int or double) or objects. Once created, its length cannot change. In contrast, an ArrayList is a resizable, object-only collection found in the java.util package. It provides methods to dynamically add and remove elements, making it flexible but slightly slower for random access. On the FRQ, you must choose the appropriate structure based on the problem's constraints; arrays are ideal when the size is known and static, while ArrayLists are better for collections that need to grow or shrink.

The syntax for each also differs. You declare and instantiate an array of integers as int[] list = new int[10];, whereas an ArrayList of String objects is created with ArrayList<String> words = new ArrayList<String>();. Remember that for ArrayLists, you must use the wrapper class (e.g., Integer) for primitive types. Recognizing these fundamental differences is the first step toward effective manipulation, as the FRQ often presents scenarios requiring you to work with one or both structures.

Traversal: For Loops and For-Each Loops

Traversing, or looping through, every element in a collection is a universal task. You have two primary tools: the standard for loop and the enhanced for-each loop. A standard for loop uses an index variable to access each position. For an array named data, you would write: for (int i = 0; i < data.length; i++) { // access data[i] }. For an ArrayList named list, you use the size() method: for (int i = 0; i < list.size(); i++) { // access list.get(i) }. This loop gives you complete control over the index, which is essential for tasks that require knowing the position, such as modifying specific elements or comparing adjacent items.

The enhanced for-each loop simplifies traversal when you only need the elements, not their indices. The syntax is for (Type element : collection) { // use element }. For example, for (int num : data) iterates over an array of integers, and for (String s : list) iterates over an ArrayList of strings. This loop is cleaner and less error-prone for read-only operations, but it has a critical limitation: you cannot use it to add or remove elements from the collection you are iterating over, as it will cause a ConcurrentModificationException. On the FRQ, use for-each for simple traversals like finding a sum or maximum, and use standard for loops when you need to modify elements or access indices.

Essential ArrayList Methods

The power of an ArrayList comes from its built-in methods. You must be fluent with add, remove, get, set, and size. The add(E element) method appends an element to the end, while add(int index, E element) inserts it at a specific position, shifting subsequent elements to the right. The remove(int index) method deletes the element at that index and shifts all later elements left to fill the gap, which is the source of common index-shifting errors. To access or modify an element, use get(int index) to retrieve it and set(int index, E element) to replace it. Finally, size() returns the number of elements, analogous to an array's .length property.

Consider this scenario: you have an ArrayList scores containing [85, 90, 78]. Calling scores.add(1, 88); changes it to [85, 88, 90, 78]. Then, scores.set(2, 95); updates it to [85, 88, 95, 78]. Calling scores.remove(0); removes the first element, resulting in [88, 95, 78]. Notice how each removal or insertion at an index affects the positions of other elements—this behavior is central to many FRQ problems. Always trace these changes carefully in your reasoning.

Managing Index-Shifting During Removal

A frequent and tricky FRQ task requires removing certain elements from an ArrayList based on a condition. The pitfall arises if you use a standard forward loop. Imagine you want to remove all even numbers from an ArrayList nums using for (int i = 0; i < nums.size(); i++). If you remove the element at index , every element after it shifts left by one position. However, your loop increments on the next iteration, causing you to skip the element that just moved into the current index. This is the index-shifting error.

The standard solution is to iterate backward through the list. Start at the last index and move toward the first: for (int i = nums.size() - 1; i >= 0; i--). When you remove an element at index , the elements that shift left are at indices less than , which you have already processed, so no elements are missed. For example, to remove all strings of length less than 3 from an ArrayList words, you would write:

for (int i = words.size() - 1; i >= 0; i--) {
    if (words.get(i).length() < 3) {
        words.remove(i);
    }
}

This backward traversal is a key pattern you must internalize for the exam. Alternatively, you can build a new ArrayList containing only the desired elements, which avoids shifting altogether but uses extra space.

Implementing Common FRQ Tasks

Beyond basic manipulation, FRQ problems often ask you to filter, search, or transform data. Filtering involves selecting elements that meet a criteria, often resulting in a new array or ArrayList. For instance, given an array of temperatures, you might need to return a new ArrayList containing only those above a threshold. This typically requires traversing the original collection, checking each element, and using add to populate a new ArrayList.

Searching tasks require finding a specific element or its position. A linear search loop that returns the first index where a condition is true is common. Remember to handle the case where no element is found, often by returning -1 or null. Transforming data means creating a modified version of the original collection. For example, you might need to create a new array where each element is doubled, or an ArrayList where strings are converted to uppercase. This involves creating a new collection of the appropriate size, traversing the original, applying the operation, and storing the result.

Consider a concrete FRQ-style problem: "Write a method removeDuplicates that accepts an ArrayList of integers and modifies it by removing all duplicate values, leaving only the first occurrence of each number." A solution involves nested loops or a helper structure, but careful index management is key. You would likely use an outer loop to hold a candidate element and an inner backward loop to scan and remove later duplicates. Practicing these patterns with timed exercises is the best way to prepare for the variety of tasks the exam presents.

Common Pitfalls

  1. Index-Shifting Errors During Forward Removal: As detailed, removing elements while iterating forward with a standard for loop causes skipped elements. Correction: Always iterate backward from the last index to the first when removing multiple elements by index.
  2. Off-by-One Errors in Loop Conditions: Using <= instead of < when comparing an index to array.length or list.size() will throw an ArrayIndexOutOfBoundsException or IndexOutOfBoundsException. Correction: Remember that valid indices run from 0 to size() - 1 or length - 1. Test loop conditions with edge cases like empty collections.
  3. Confusing Array .length with ArrayList .size(): Using arr.size() or list.length() is a syntax error that will prevent your code from compiling. Correction: length is a field for arrays; size() is a method for ArrayLists. Drill this distinction into your memory.
  4. Modifying a Collection During a For-Each Loop: Attempting to add or remove an element from a list while using a for-each loop results in a runtime ConcurrentModificationException. Correction: Use a standard for loop with index control for any traversal that involves structural modification.

Summary

  • FRQ 3 Focus: Array and ArrayList manipulation is the hallmark of AP CSA FRQ 3, requiring precise control over traversal, modification, and logic.
  • Traversal Trade-offs: Use standard for loops when you need the index or plan to modify the collection; use enhanced for-each loops for simpler, read-only processing of elements.
  • ArrayList Mastery: Be fluent with add, remove, get, set, and size, understanding that remove and add (at an index) cause elements to shift.
  • Critical Pattern: To safely remove multiple elements from an ArrayList, always iterate backward with for (int i = list.size() - 1; i >= 0; i--).
  • Task Strategies: Filtering, searching, and transforming often involve creating new collections or carefully managed in-place edits—plan your approach by determining if the original data must be preserved.
  • Avoid Classic Errors: Steer clear of index-shifting in forward loops, off-by-one conditions, and syntax mix-ups between arrays and ArrayLists to ensure your code compiles and runs correctly.

Write better notes with AI

Mindli helps you capture, organize, and master any subject with AI-powered summaries and flashcards.