Unit 7: ArrayList
AP Computer Science A: 49 practice questions with detailed explanations.
Unit Study Guide
Executive Summary
ArrayList grows and shrinks at runtime, storing objects (Integer, not int). It is the dynamic alternative to arrays.
Creation and generics
ArrayList<Integer> list = new ArrayList<Integer>() stores Integer objects thanks to autoboxing. size() reports how many elements exist; indexes again run 0 to size() - 1.
Core methods
add(value) appends. add(index, value) inserts and shifts the rest right. get(index) reads. set(index, value) replaces and returns the old value. remove(index) deletes, shifts the rest left, and returns the removed element. size() is the count.
Traversals
Use an indexed loop to read AND write. Enhanced for works for reading only. Removing while traversing forward skips elements — go backward or adjust the index.
Searching and algorithms
Linear search with get(index). Find min/max with a running comparison. Sum with an accumulator. Reversal swaps the first half with mirrored positions.
Exam traps
remove(int) removes by INDEX on an Integer list, not by value. get(size()) throws IndexOutOfBoundsException. add at the front shifts everything, which is why appending is cheaper than inserting.