Topic 4.10 — ArrayLists and Arrays
Goal: compare arrays vs ArrayLists, understand how to move between them (conceptually), and recognize which structure is better for a given problem.
The big idea
Arrays and ArrayLists both store ordered sequences, but they have different strengths: arrays are fixed-size, while ArrayLists can grow/shrink.
On AP CSA, you’ll often be asked to trace code and reason about indexing + method behavior.
Quick comparison
| Feature | Array | ArrayList |
|---|---|---|
| Size | fixed after creation | changes dynamically |
| Length/size | arr.length | list.size() |
| Read | arr[i] | list.get(i) |
| Update | arr[i] = x | list.set(i, x) |
| Add/remove in middle | you must shift manually | add(i,x) / remove(i) shifts for you |
When arrays are a better fit
- You know the exact number of items up front
- You want simple fixed indexing with minimal overhead
- You don’t need insert/remove operations often
int[] scores = new int[5];
When ArrayLists are a better fit
- You don’t know how many items there will be
- You need to add/remove as you go
- You want convenient methods for shifting elements
ArrayList<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
Same concept: traversal
Both can be traversed with a normal indexed loop.
// array
for (int i = 0; i < arr.length; i++) {
// use arr[i]
}
// ArrayList
for (int i = 0; i < list.size(); i++) {
// use list.get(i)
}
Same indexes, different syntax
- Arrays use
[]for read/write - ArrayLists use methods (
get,set)
// array update
arr[i] = 99;
// ArrayList update
list.set(i, 99);
Copy idea: ArrayList → array (concept)
A common pattern is creating an array of the same size and copying each element over. (You might see this as an algorithm or reasoning task.)
int[] a = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
a[i] = list.get(i);
}
Copy idea: array → ArrayList (concept)
Add each element into a new list.
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Important: what ArrayLists store
ArrayLists store objects, not primitives—so you use wrapper classes like Integer.
Autoboxing/unboxing often happens automatically in AP problems.
ArrayList<Integer> nums = new ArrayList<>();
nums.add(7); // autobox int -> Integer
int x = nums.get(0); // unbox Integer -> int
Quick self-check
- How do you get the number of elements in an array? In an ArrayList?
- What’s the difference between
arr[i]andlist.get(i)? - Which structure is easier when you need to insert/remove a lot?
- Why does
ArrayList<int>not work? - Write the traversal loop for both an array and an ArrayList.