Unit 4 Cycle 1 Day 10: ArrayList Creation and Methods

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

ArrayList Creation and Methods

Section 4.4 — ArrayList Methods

Key Concept

An ArrayList is a resizable collection that stores objects (not primitives). Creation: ArrayList list = new ArrayList<>(). Key methods: add(item) appends to the end, add(index, item) inserts at a position shifting subsequent elements, get(index) retrieves an element, set(index, item) replaces an element, remove(index) removes and returns the element at a position, and size() returns the number of elements. Unlike arrays, ArrayList grows and shrinks dynamically.

Consider the following code segment.

ArrayList list = new ArrayList(); list.add("A"); list.add("B"); list.add("C"); list.add(1, "X"); System.out.println(list);

What is printed?

Answer: (A) [A, X, B, C]

After three adds: [A, B, C]. add(1, "X") inserts "X" at index 1, shifting B and C right: [A, X, B, C].

Why Not the Others?

(B) "X" goes at index 1, pushing B from index 1 to index 2.

(C) "X" is inserted at index 1, not index 0.

(D) add(1, "X") inserts at index 1, not at the end.

Common Mistake

add(value) appends to the end. add(index, value) inserts at the specified index, shifting existing elements right.

AP Exam Tip

Two forms of add: add(e) adds to end, add(i, e) inserts at index i. Know both for the AP exam. The insert form shifts all elements from index i onward.

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.