Unit 4 Cycle 1 Day 12: ArrayList set() and get()

Unit 4 Foundation (Cycle 1) Day 12 of 28 Foundation

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.

ArrayList nums = new ArrayList(); nums.add(10); nums.add(20); nums.add(30); nums.set(1, 99); System.out.println(nums.get(0) + nums.get(1) + nums.get(2));

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.

Review this topic: Section 4.4 — ArrayList Methods • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.