Implementing
ArrayList Algorithms
Master the core algorithms for traversing, inserting, removing, and searching elements using Java's ArrayList.
What is an ArrayList?
An ArrayList is a resizable array implementation of the List interface in Java. Unlike a standard array, its size grows and shrinks automatically as elements are added or removed.
Essential ArrayList Methods
Visualizing Insert & Remove
Traversal Patterns
Forward vs Backward Traversal
| Forward (from index \(0\)) | Backward (from index \(\text{size()}-1\)) | |
|---|---|---|
| Direction | Left to right | Right to left |
| Use for | General reading, searching | Removing elements safely |
| Index after remove | Elements shift: skip risk | Already-visited elements shift |
| Pattern | i = 0; i < size(); i++ | i = size()-1; i >= 0; i-- |
The Traverse-Check-Act Pattern
How to Apply the Pattern
Example: Remove All Negatives
Given an ArrayList<Integer>, remove every element that is less than zero.
Tracing the Removal
Example: Linear Search
Find the index of the first occurrence of a target value. Return -1 if not found.
Example: Sum & Average
The accumulator pattern initializes a running total, then adds each element's contribution during traversal.
Example: Filtering into a New List
Sometimes the goal is to create a new list of elements that meet a condition, leaving the original unchanged.
Advanced: Simultaneous Traversal
When comparing two ArrayLists element-by-element, traverse both at once using a standard for loop up to the smaller size.
Common Mistakes
Algorithm Summary
| Algorithm | Loop Type | Direction | Key Method |
|---|---|---|---|
| Linear Search | Standard for | Forward | .get(), .equals() |
| Remove by condition | Standard for | Backward | .remove(\(i\)) |
| Accumulate (sum, count) | Enhanced for | Forward | \( \text{+=} \) operator |
| Filter to new list | Enhanced for | Forward | .add() |
| Insert at position | Standard for | Forward | .add(\(i\), elem) |
| Compare two lists | Standard for | Forward | Math.min(), .get() |
Question 1 of 5
What is the output of the following code?ArrayList<Integer> list = new ArrayList<>();
list.add(10); list.add(20); list.add(30);
list.add(1, 15);
System.out.println(list);
Question 2 of 5
You want to remove all occurrences of the String "spam" from an ArrayList. Which loop structure is safest?
Question 3 of 5
Consider this code fragment:ArrayList<String> words = /* initialized */;
for (int i = 0; i < words.size(); i++) {
if (words.get(i).length() <= 3) {
words.remove(i);
}
}
If words starts as ["hi", "hello", "go", "yes"], what is the result?
Question 4 of 5
What is the time complexity of calling list.add(0, element) on an ArrayList with \( n \) elements?
Question 5 of 5
Which line of code correctly checks if element at index \( i \) in an ArrayList<String> equals the String "target"?