Topic 4.5 — ArrayList Creation and Access
Goal: create ArrayList objects, understand how they store references, and access/update elements using
get and set.
The big idea
An ArrayList is a resizable list. Unlike arrays, it can grow and shrink.
You still use zero-based indexing, but you access elements with methods like
get and set.
If you’re thinking “array, but flexible,” you’re on the right track.
ArrayList vs Array (quick compare)
| Feature | Array | ArrayList |
|---|---|---|
| Size changes? | No (fixed) | Yes (resizable) |
| Length/size | arr.length |
list.size() |
| Access | arr[i] |
list.get(i) |
| Update | arr[i] = x |
list.set(i, x) |
Create an ArrayList
You usually use generics: ArrayList<Type>. In AP CSA, you’ll often see
ArrayList<Integer> and ArrayList<String>.
import java.util.ArrayList;
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> words = new ArrayList<String>();
Important: primitives vs wrapper classes
ArrayLists store objects, not primitives.
| Primitive | Wrapper (object) |
|---|---|
int | Integer |
double | Double |
boolean | Boolean |
So you write ArrayList<Integer>, not ArrayList<int>.
Size and indexes
- First index is
0. - Last index is
list.size() - 1. size()is a method (parentheses required).
int n = nums.size();
Out of bounds (still a thing)
If you use an invalid index, you’ll get an exception (similar idea to arrays).
ArrayList<String> list = new ArrayList<String>();
list.get(0); // ❌ list is empty
Access and update: get and set
ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Linus");
// Access:
String first = names.get(0); // "Ada"
// Update (replaces existing value):
names.set(1, "Grace"); // now ["Ada", "Grace"]
set(i, value) overwrites what’s already at index i.
ArrayList stores references
For object types, the list stores references to objects. If two variables refer to the same object, changes to that object are visible through both references.
// Example idea (details depend on class):
// Two references can point to the same object.
What you should be able to do on AP
- Create an ArrayList with a type parameter
- Use
size()correctly - Access values with
get - Replace values with
set - Recognize index bounds:
0tosize()-1
Quick self-check
- Why do we use
Integerinstead ofintin an ArrayList? - What’s the last valid index if
list.size()is 7? - What does
set(i, x)do? - How is
list.get(i)different fromlist.set(i, x)? - Why is
list.lengthincorrect?