Unit 4 Cycle 1 Day 12: ArrayList set() and get()
Share
ArrayList set() and get()
Section 4.4 — ArrayList Methods
Key Concept
The set() method replaces the element at a specified index and returns the old value: String old = list.set(2, "new"). The get() method retrieves without modifying. Both throw IndexOutOfBoundsException if the index is invalid. On the AP exam, set() is tested in replacement algorithms where you iterate through a list and replace elements that meet a condition. Remember that set() does not shift elements — it overwrites in place, unlike add(index, item) which inserts and shifts.
Consider the following code segment.
What is printed?
Answer: (B) 139
After adds: [10, 20, 30]. set(1, 99) replaces index 1: [10, 99, 30]. Sum: 10 + 99 + 30 = 139.
Why Not the Others?
(A) 60 = 10+20+30, the sum before the set operation.
(C) 129 would require different values.
(D) 159 would be if 99 was added instead of replacing.
Common Mistake
set(index, value) REPLACES the element at the index. It does NOT insert a new element. The size stays the same.
AP Exam Tip
set(i, val) replaces. add(i, val) inserts. remove(i) deletes. Know the difference: set does not change size, add and remove do.