📚Study Guide: ArrayList
Unit 7: ArrayList
The ArrayList class provides a resizable-array implementation of the List interface, offering the convenience of dynamic sizing combined with fast random access. Unlike arrays, ArrayLists can grow and shrink as elements are added or removed, making them far more flexible for many applications. Students must understand the generic type parameter (ArrayList<String>) which enforces type safety at compile time. The AP exam tests ArrayList methods extensively: add (append or insert), remove (by index or object), get, set, size, and clear. Understanding that remove(int index) returns the removed element and shifts subsequent elements left is crucial. The set(int index, E element) method replaces an element but does not insert. When iterating over an ArrayList, the enhanced for loop is convenient but cannot modify the list structure safely; for structural modifications (adding/removing during iteration), a standard for loop traversing backwards is often safest to avoid index shifting issues. Searching and sorting algorithms using ArrayLists are common free-response topics. Students must also recognize autoboxing: adding an int to an ArrayList<Integer> automatically converts the primitive to an Integer object. The ArrayList is the workhorse collection for the AP CSA exam, and mastery of its API and traversal patterns is non-negotiable for a top score.
Key Concepts
- ArrayList Basics: ArrayList<Type> list = new ArrayList<Type>(); Type must be a reference type (object or wrapper). Diamond operator <> allows type inference: new ArrayList<>().
- Core Methods: add(E obj) appends. add(int index, E obj) inserts and shifts right. get(int index) returns element. set(int index, E obj) replaces element. remove(int index) removes and returns element, shifting left. remove(Object obj) removes first occurrence. size() returns number of elements. clear() removes all.
- Traversal: Enhanced for: for (String s : list) { ... }. Standard for: for (int i = 0; i < list.size(); i++) { ... }. When removing multiple elements, traverse backwards to avoid skipping elements.
- Wrapper Classes and Autoboxing: ArrayList<Integer> stores Integer objects. list.add(5) autoboxes int 5 to Integer.valueOf(5). int x = list.get(0) auto-unboxes.
- Search and Sort: Sequential search scans list. For sorting, the AP exam may ask students to implement selection sort or insertion sort using ArrayList methods.
Vocabulary
- Generic Type: A feature of Java classes and methods that allows types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.
- Autoboxing: The automatic conversion by the Java compiler of primitive types to their corresponding object wrapper classes (e.g., int to Integer).
- Auto-unboxing: The automatic conversion by the Java compiler of wrapper class objects back to their corresponding primitive types (e.g., Integer to int).
- Resizable Array: An underlying array that grows automatically as elements are added, typically by creating a larger array and copying existing elements.
- Sequential Search: Searching a list by examining each element in order until the target is found or the end is reached.
- ConcurrentModificationException: A runtime exception thrown when a collection is modified structurally during iteration (except through the iterator's own methods).
Essential Formulas / Syntax Patterns
- ArrayList<String> list = new ArrayList<>();
- list.add("hello");
- String s = list.get(0);
- list.set(1, "world");
- list.remove(0);
- for (int i = list.size() - 1; i >= 0; i--) { ... }
Common Mistakes
- Using Arrays with ArrayList Syntax: ArrayLists use .get(index), .size(), and .add(). Arrays use [index], .length, and cannot add/remove.
- Confusing remove(int) and remove(Object): list.remove(2) removes the element at index 2. To remove Integer 2, use list.remove(Integer.valueOf(2)).
- Modifying During Enhanced for: Adding or removing elements in an enhanced for loop causes ConcurrentModificationException. Use a standard for loop or iterator.
- Forgetting Autoboxing with Primitives: ArrayList<int> is invalid. Must use ArrayList<Integer>. However, autoboxing handles most conversions automatically.
AP Exam Strategies
- Traverse Backwards When Removing: To avoid index shifting errors when removing multiple elements, loop from list.size() - 1 down to 0.
- Use get() and set() for Random Access: ArrayList provides O(1) access by index. Use these instead of searching when you know the position.
- Remember Size Changes: After add(), size increases. After remove(), size decreases. Any code depending on the original size must be recalculated.
- Implement Sorting Algorithms: Be prepared to write selection sort or insertion sort on ArrayLists using compareTo and swap logic.
Real-World Applications
- Shopping Carts: E-commerce sites use ArrayLists to hold dynamically changing collections of items before checkout.
- Contact Lists: Mobile apps store contacts in ArrayLists because users add, delete, and reorder entries frequently.
- Dynamic Data Buffers: Network protocols buffer incoming packets in resizable ArrayLists before processing complete messages.