Source: Princeton Review AP CS A Prep, 8th Edition
Tags: Java arrays, ArrayList, array traversal, for-each loop, array manipulation, ArrayList methods, add, remove, get, set, size, IndexOutOfBoundsException, autoboxing, AP Computer Science A, Unit 6, Unit 7
Difficulty: Intermediate Prerequisites: Java Fundamentals, Iteration and Loops.
Arrays and ArrayLists are the two primary ways to store collections of data in AP CS A. Arrays have a fixed size and use bracket notation (arr[i]), while ArrayLists can grow and shrink dynamically and use method calls (list.get(i)). The exam tests traversal, modification, searching, and common pitfalls like index shifting during removal. Understanding the difference between modifying an array element through its index vs. through a for-each loop variable is critical. These units also introduce the idea that assigning one array variable to another does not copy the array; it creates a second reference to the same data.
Arrays are fixed-size, zero-indexed, and accessed with brackets. ArrayLists are resizable, zero-indexed, and accessed with methods. Removing elements from an ArrayList during traversal shifts indices and is a common source of bugs. A for-each loop gives you a copy of each element; modifying that copy does not change the original array.
Array
A fixed-size, ordered collection of elements of the same type. Declared as int[] arr = new int[5]; or int[] arr = {1, 2, 3};. Indexed from 0 to length - 1.
length (array property)
Returns the number of elements in an array. Note: it is a field, not a method. No parentheses: arr.length, not arr.length().
ArrayList
A resizable, ordered collection from java.util. Declared as ArrayList. Uses generics to specify the element type.
Autoboxing / unboxing
Java automatically converts between primitives and their wrapper classes. int becomes Integer when added to an ArrayList, and vice versa. This happens transparently but is worth knowing.
add(E obj)
Appends obj to the end of the ArrayList. Returns true.
add(int index, E obj)
Inserts obj at position index, shifting existing elements to the right. Valid indices: 0 to size().
get(int index)
Returns the element at position index.
set(int index, E obj)
Replaces the element at index with obj. Returns the element that was previously there.
remove(int index)
Removes and returns the element at index. All elements to the right shift left by one, and size() decreases by one.
size() (ArrayList method)
Returns the number of elements currently in the list. Note: it is a method with parentheses, unlike arr.length.
Index shifting
When you remove(i) from an ArrayList, elements at positions i + 1, i + 2, etc. all move down by one. If you are iterating forward with i++, you will skip the element that just moved into position i.
For-each loop (enhanced for loop)
for (int element : arr) iterates over each element in the array or list. The loop variable element is a local copy. Assigning to it does not modify the original collection.
Array aliasing
int[] arr2 = arr1; does not copy the array. Both arr1 and arr2 point to the same array in memory. Changes through either variable affect the same data.
int[] nums = {11, 22, 33, 44, 55, 66}; then nums[nums[i] / 11] = nums[i]; modifies the array in place. Trace carefully: when i = 0, nums[0] / 11 = 1, so nums[1] = nums[0] = 11. The array changes as you go, and later iterations use the already-modified values.
After full execution: {11, 11, 22, 33, 33, 55}. Each step overwrites an element using the current (possibly already modified) state.
int[] arr2 = arr1; makes arr2 an alias for arr1. They share the same underlying data.
arr2[i] = arr1[last - i]; modifies the shared array. So when you later print arr1, you see the modified values.
Example: arr1 = {1, 2, 3, 4, 5, 6}, arr2 = arr1, then arr2[i] = arr1[5 - i] for each i. At i = 0: arr2[0] = arr1[5] = 6. But arr1 IS arr2, so arr1[0] is now 6. At i = 1: arr2[1] = arr1[4] = 5. Continue through. The result is {6, 5, 4, 4, 5, 6} printed twice (since both variables reference the same array).
for (int element : arr3) { element *= 2; System.out.print(element + " "); } prints doubled values (2, 4, 6, 8, 10, 12) but does NOT modify arr3.
Printing arr3 afterwards shows the original values: {1, 2, 3, 4, 5, 6}.
The output is two lines: 2 4 6 8 10 12 then 1 2 3 4 5 6.
Initialising holdSmallest = Integer.MAX_VALUE and holdLargest = 0 (or Integer.MIN_VALUE for a proper version) is a common pattern.
The code tracks both the values and their indices. If holdLargest is initialised to 0, it will only correctly find the largest value if all values are non-negative. Negative values would never satisfy numbers[i] >= 0.
This is a deliberate design flaw tested in the exam: the code finds the location of the smallest value and the location of the largest non-negative value.
int sum = 0; for (int element : sales) { sum += element; } double avg = (double) sum / sales.length;
The cast (double) must be applied to sum before the division. Without it, integer division truncates the result.
Using sales[i] inside a for-each loop is incorrect because there is no index variable i. Use element directly.
swap1 uses a temp variable and iterates through both arrays element by element: int hold = a1[i]; a1[i] = a2[i]; a2[i] = hold;. This works correctly when both arrays have the same number of elements (iterates using a1.length). If a2 is longer, extra elements are ignored. If a2 is shorter, ArrayIndexOutOfBoundsException.
swap2 tries to swap the array references: int[] hold = a1; a1 = a2; a2 = hold;. This only reassigns the local parameter variables. The caller's original variables remain unchanged. So swap2 never works.
Building an ArrayList from an array: for (int a : a1) { alist.add(a); }.
Removing elements during forward iteration: for (int i = 0; i < alist.size(); i++) { if (alist.get(i) % 2 == 0) { alist.remove(i); } }. After removing at index i, the element that was at i + 1 shifts to i, but i increments, so that element is skipped.
For {2, 4, 6, 7, 8, 10, 11}: remove index 0 (value 2), list becomes {4, 6, 7, 8, 10, 11}, i becomes 1. At index 1: value 6, remove. List becomes {4, 7, 8, 10, 11}, i becomes 2. At index 2: value 8, remove. List becomes {4, 7, 10, 11}, i becomes 3. At index 3: value 11, odd, skip. Final: {4, 7, 10, 11}. But since original was {2, 4, 6, 7, 8, 10, 11}, the answer is [4, 7, 10, 11].
ArrayList compiles. "4.5" is a valid String.
ArrayList compiles. (int) 4.5 is 4, autoboxed to Integer.
ArrayList compiles. 4.5 is autoboxed to Double.
All three compile. The key is matching the declared type with the argument type (after autoboxing/casting).
The practice test shows a bubble sort using remove and add. For each pass, adjacent elements are compared, and if out of order, the smaller one is removed and reinserted.
Counting how many times a comparison line executes requires tracking the inner loop bounds as the list conceptually shrinks (though in this implementation, the size stays constant since we remove and re-add).
Arrays back every data buffer, pixel grid, and sensor reading in real systems. ArrayLists (and similar dynamic lists) power shopping carts, search results, and message queues where the number of items is not known in advance. The index-shifting problem during removal is a real-world bug source in any language with similar list semantics.
Students assume int[] arr2 = arr1 creates a copy. It does not. Both variables point to the same array. To copy, you must iterate and copy each element, or use Arrays.copyOf.
Modifying a for-each loop variable is a very common mistake. element *= 2 inside for (int element : arr) changes only the local copy, not the array.
When removing from an ArrayList during forward iteration, students forget about index shifting. The classic fix is to iterate backwards, or to decrement i after a removal.
Confusing arr.length (no parentheses, for arrays) with list.size() (with parentheses, for ArrayLists). Mixing them up causes compiler errors.
⚠️ Array aliasing (two variables pointing to the same array) is a favourite trick question. If you see arr2 = arr1 followed by modifications, both variables reflect the changes.
⚠️ For-each loop modification is tested directly: "what is the array after this loop?" The answer is always "unchanged."
⚠️ ArrayList removal during forward iteration and the resulting index skip is tested in nearly every exam. Trace carefully.
⚠️ The difference between arr.length and list.size() is a small but frequently tested detail.
⚠️ Autoboxing/unboxing between int/Integer and double/Double is assumed knowledge for ArrayList questions.
True or false: int[] b = a; creates a new copy of array a.
Fill in the blank: To get the number of elements in an array, use arr.______; for an ArrayList, use list.______().
True or false: Removing an element from an ArrayList at index i causes all elements after it to shift left by one.
Fill in the blank: ArrayList stores ________ objects, not primitive int values, though autoboxing handles the conversion.
True or false: for (int x : myArray) { x = 0; } sets every element of myArray to 0.
Q: After int[] arr1 = {1,2,3,4,5,6}; int[] arr2 = arr1; int last = 5; for (int i = 0; i < 6; i++) arr2[i] = arr1[last - i];, what does printing arr1 show?
A: 6 5 4 4 5 6. Since arr2 IS arr1, modifications happen in place. By the time i = 3, arr1[0] is already 6, so arr1[3] = arr1[2] uses the already-modified value of arr1[2], which is 4.
Q: Which code correctly computes the average of the sales array inside a for-each loop?
A: sum += element; inside the loop body, followed by double avg = (double) sum / sales.length; after the loop. You must use element (not sales[i], since there is no i), and cast sum to double before dividing.
Q: After removing all even numbers from ArrayList [2,4,6,7,8,10,11] using a forward-iterating loop with i++, what remains?
A: [4, 7, 10, 11]. The forward iteration skips elements that shift into the just-removed position. Elements 4, 10 survive because they shift into a position the loop has already passed.
Arrays connect to 2D arrays (Unit 8), which are simply arrays of arrays. ArrayLists are used extensively in the free-response section for managing collections of objects. Sorting and searching algorithms (Unit 10) operate on arrays. Understanding reference behaviour for arrays prepares you for the same concept with objects in inheritance (Unit 9).
array, ArrayList, java.util.ArrayList, array traversal, for-each loop, enhanced for loop, array aliasing, array copy, index shifting, remove during iteration, add, get, set, remove, size, length, autoboxing, unboxing, wrapper class, Integer, Double, IndexOutOfBoundsException, ArrayIndexOutOfBoundsException, bubble sort, selection sort, AP CS A Unit 6, AP CS A Unit 7