Unit 4 Cycle 2 Day 11: I/II/III: ArrayList Operations
Share
I/II/III: ArrayList Operations
Section 4.4 — ArrayList Methods
Key Concept
I/II/III ArrayList operations questions test behavior of add(), remove(), set(), and get() in specific scenarios. Key facts: add(index, item) shifts elements right and increases size by 1, remove(index) shifts elements left and decreases size by 1, set(index, item) replaces without changing size, and all throw IndexOutOfBoundsException for invalid indices. Evaluate each statement by tracing the operation on a specific list and checking whether the claimed result matches.
Given ArrayList, consider these operations applied independently.
Which statements correctly describe the result?
Answer: (B) I, II, and III
I: TRUE. add(2,12) inserts at index 2, shifting 15 and 20 right. Size becomes 5.
II: TRUE. set(2,12) replaces 15 with 12. Size stays 4.
III: TRUE. remove(2) removes 15. Size becomes 3.
Why Not the Others?
(A) II is also true.
(C) I is also true.
(D) II and III are also true.
Common Mistake
add = insert (size+1). set = replace (same size). remove = delete (size-1). Three different behaviors at the same index.
AP Exam Tip
Know exactly how add, set, and remove affect both the list contents and its size.