1 Answers
📚 Quick Study Guide: ArrayList Element Removal
- ✂️ `remove(int index)`: Removes the element at the specified index. All subsequent elements are shifted to the left, and their indices decrease by one. This method returns the element that was removed.
- 🎯 `remove(Object obj)`: Removes the *first* occurrence of the specified object from the list. If the list does not contain the element, it remains unchanged. Returns `true` if the element was removed, `false` otherwise.
- 🔄 Iteration Caution: When removing elements by index within a loop, it's generally safer and more efficient to iterate backwards from the end of the list. Iterating forwards can lead to skipping elements or `IndexOutOfBoundsException` due to element shifting.
- ⏱️ Efficiency: Removing elements from the middle or beginning of a large `ArrayList` is an $O(N)$ operation because it requires shifting all subsequent elements. Removing from the end is $O(1)$.
- ⚠️ Autoboxing Alert: Be extremely careful with `remove()` and `Integer` objects. If `list` contains `Integer` objects, `list.remove(5)` will attempt to remove the element at index `5`. To remove the `Integer` object with value `5`, you must cast it: `list.remove((Object) 5)`.
🧠 Practice Quiz: ArrayList Removal Skills
1. What is the primary effect on the indices of elements in an `ArrayList` when `remove(int index)` is called?
- Indices of all elements after the removed one increase by one.
- Indices of all elements after the removed one decrease by one.
- Indices of elements remain unchanged, but the list size decreases.
- The `ArrayList` is re-indexed from scratch.
2. Consider an `ArrayList
- `["Alice", "Charlie", "David"]`
- `["Bob", "Charlie", "David"]`
- `["Alice", "Bob", "David"]`
- `["Alice", "Charlie", "Bob", "David"]`
3. If an `ArrayList
- `[10, 30, 20, 40]`
- `[10, 20, 30, 40]`
- `[10, 30, 40]`
- `[10, 20, 30, 20, 40]` (no change)
4. Which of the following is the *safest and most recommended* way to remove elements from an `ArrayList` while iterating through it, especially when removing based on a condition?
- Iterating forwards using a standard `for` loop with `list.remove(i)`.
- Iterating backwards using a standard `for` loop with `list.remove(i)`.
- Using an enhanced `for` loop and calling `list.remove()`.
- Using an `Iterator` and its `remove()` method.
5. An `ArrayList
- `"banana"`
- `true`
- `false`
- `null`
6. Given `ArrayList
- `[1, 2, 5]`
- `[1, 3, 5]`
- `[1, 2, 4]`
- `[1, 3, 4]`
7. What is the time complexity of removing an element from the *beginning* of an `ArrayList` in the worst-case scenario?
- $O(1)$
- $O(\log N)$
- $O(N)$
- $O(N^2)$
Click to see Answers
1. B
2. A
3. A
4. D
5. B
6. A
7. C
Join the discussion
Please log in to post your answer.
Log InEarn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! 🚀