📖 Crammy · All study guides
AP Computer Science A · Unit 7

ArrayList: every key term you need (+ practice quiz)

52 flashcard terms for AP Computer Science A Unit 7, written to match the course framework. Read them here, drill them as flashcards, or take the 42-question quiz. Free, no account needed.

Study this unit free →

More AP Computer Science A guides

ArrayList
Resizable array; grows/shrinks dynamically. ArrayList<Type> list = new ArrayList<>();. Type: Integer, String, custom classes.
ArrayList Methods
add(object): append. add(index, object): insert. remove(index): delete. get(index): access. size(): count. clear(): empty list.
ArrayList Type Parameter
<String> indicates ArrayList holds Strings. ArrayList<int> invalid (must use Integer). Generic type ensures type safety.
ArrayList Indexing
get(index) returns element; set(index, object) replaces. Index 0 to size()-1. Index out of range throws exception.
ArrayList vs Array
ArrayList: dynamic size, objects only, slower. Array: fixed size, primitives OK, faster. Choose based on needs.
Autoboxing/Unboxing
Automatic conversion: primitive ↔ wrapper class. int → Integer, double → Double. Enables primitives in generics.
ArrayList Iteration
For loop: for(int i=0; i<list.size(); i++) list.get(i). Enhanced for: for(String s : list). Iterator: while(it.hasNext()).
ArrayList Algorithms
Search: linear search with get(). Sort: Collections.sort(list). Min/max: Collections.min/max(list).
Removing Elements
remove(index): removes and shifts. remove(Object): removes first match. Modifying while iterating: use iterator.remove().
Unit 7 Summary
ArrayList dynamic, resizable. Methods: add, remove, get, size. Type parameter specifies element type. Autoboxing converts primitives.
add(index, element) Shifting
Inserts at the given index and shifts later elements right; index may equal size() to append. Any larger index throws IndexOutOfBoundsException.
remove(index) Returns the Element
Removes and returns the element at index, shifting later elements left and reducing size by one. For ArrayList<Integer>, remove(int) uses the index, not the value.
set(index, element) Returns Old Value
Replaces the element and returns what was there. Size is unchanged. set on an empty list throws even for index 0.
Remove-while-traversing Bug
Removing element i in a forward loop shifts the next element into position i, which then gets skipped. Fix by traversing backward or by not incrementing i after a removal.
Add-while-traversing Risk
Adding elements during a forward indexed loop lengthens the list and may loop forever if the bound is size(). Adding during an enhanced for loop throws ConcurrentModificationException.
Enhanced for on ArrayList
for (String s : list) is legal for reading and for calling mutators on the objects, but structural changes (add/remove) inside it throw ConcurrentModificationException.
Autoboxing in ArrayList<Integer>
list.add(5) boxes 5 into an Integer; int x = list.get(0) unboxes. Comparing list.get(i) == list.get(j) compares references and can be false for equal values above 127.
Generic Type Parameter
ArrayList<String> restricts contents to Strings and lets get return String without a cast. Only class types are allowed, hence Integer and Double rather than int and double.
Drill these as interactive flashcards →
size() vs length
ArrayList uses the size() method; arrays use the length field; String uses length(). Mixing them up is a compile error.
Traversal Bound Re-evaluated
for (int i = 0; i < list.size(); i++) recomputes size() every pass, so it adapts as the list shrinks or grows. Caching the size in a variable can cause out-of-bounds errors after removals.
Insertion Order Building
To build a list in reverse, add each new element at index 0; to keep sorted order, scan for the first larger element and insert before it.
Removing All Occurrences
for (int i = list.size() - 1; i >= 0; i--) if (list.get(i).equals(target)) list.remove(i); Backward traversal keeps unvisited indices stable.
contains and indexOf
contains(obj) and indexOf(obj) use equals internally. They are not part of the required subset but are commonly seen; on the exam write the loop explicitly.
Sequential Search on ArrayList
for (int i = 0; i < list.size(); i++) if (list.get(i).equals(target)) return i; return -1; Use equals for objects, not ==.
Selection Sort
For each position i, find the index of the smallest remaining element from i to end and swap it into position i. Always about n^2/2 comparisons regardless of input order.
Insertion Sort
For each element from index 1 onward, shift larger elements to the right until the correct slot is found and insert. Fast on nearly-sorted data; worst case about n^2/2 shifts.
Selection vs Insertion Sort Contrast
Selection sort does at most n - 1 swaps but always all comparisons; insertion sort's work depends on how sorted the input is. Both are O(n^2) in the worst case.
Sorting Stability (Beyond Subset)
Insertion sort keeps equal elements in their original relative order; selection sort as usually written does not. Not tested, but useful for reasoning about traces.
Data Privacy with Collections
The CED links ArrayList work to ethical concerns: lists of personal data must be protected and only collected when necessary.
Wrapper null in ArrayList<Integer>
An ArrayList<Integer> may contain null; unboxing null with int x = list.get(i) throws NullPointerException.
Backward Removal Loop
Traversing from size() - 1 down to 0 lets a loop remove elements without skipping, because shifting only affects positions already visited.
Adjusting the Index After Removal
A forward loop can remove safely if it decrements the counter after each removal, so the shifted element is examined on the next pass.
ConcurrentModificationException
Structurally changing an ArrayList while an enhanced for loop is running throws this exception, because the iterator detects the modification.
add at Index Shifts Right
list.add(2, x) moves every element from index 2 onward one position later and increases size by one; the index may equal size but not exceed it.
remove Returns the Removed Object
The single-argument index form returns the element it deleted, which is useful for moving an item between lists in one statement.
remove(int) vs remove(Object) Ambiguity
On an ArrayList<Integer>, remove(2) deletes the element at index 2 while remove(Integer.valueOf(2)) deletes the value 2.
Test yourself on this unit →
set Replaces Without Resizing
list.set(i, x) overwrites in place, returns the old element, and leaves size unchanged, unlike add which always grows the list.
Generic Type Safety
ArrayList<String> lets the compiler reject a wrong-typed add and removes the need for a cast when reading, turning a run-time failure into a compile error.
Wrapper Types Are Required
Generics accept only reference types, so a list of numbers is ArrayList<Integer> and each int is autoboxed on insertion.
Unboxing a null Element
Reading a null Integer into an int variable throws NullPointerException, which is the hazard of allowing nulls into a numeric list.
size() Re-evaluated Each Pass
A loop condition calling size() reflects insertions and deletions immediately, so adding inside the body can produce an infinite loop.
contains Uses equals
Membership testing relies on the element type's equals method, so a class without an override will match only by reference identity.
indexOf Returns the First Match
Later duplicates are ignored, and -1 signals absence, which mirrors the String and array search conventions.
Insertion Sort on a List
Each new element is moved backward past every larger neighbor; the work is small for nearly sorted data and quadratic in the worst case.
Selection Sort Swap Count
Selection sort performs at most n - 1 swaps regardless of the data, which makes it attractive when writing is far costlier than comparing.
Best and Worst Case Contrast
Insertion sort is linear on already sorted input, while selection sort scans the remaining elements every pass no matter what.
Building a Filtered List
Constructing a new list of the elements that pass a test avoids all index-shifting hazards that in-place removal creates.
Swapping Two Elements
Save one element, set its position from the other, then set the second position from the saved value; a direct double set loses data.
List of Objects and Aliasing
Adding the same object twice stores two references to one object, so a mutation is visible at both positions.
Passing an ArrayList to a Method
The reference is copied, so a method can add, remove, or modify elements and the caller observes every change.
Choosing Array or ArrayList
Use an array when the size is fixed and known, and an ArrayList when elements are inserted or removed during execution.
Traversal Cost of Insertion
Inserting at the front shifts every existing element, so repeated front insertions over n items cost about n^2 element moves.
Turn these into flashcards & quizzes →