Unit 4 Cycle 1 Day 10: ArrayList Creation and Methods
Share
ArrayList Creation and Methods
Section 4.4 — ArrayList Methods
Key Concept
An ArrayList is a resizable collection that stores objects (not primitives). Creation: 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.
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.