dev only
ArrayList and its Methods
Why ArrayList Exists
An array's size is fixed forever once created. ArrayList is Java's resizable alternative — use it whenever you don't know the final size up front, or items will be added/removed while the program runs (a growing log of events, for instance).
import java.util.ArrayList;
ArrayList<String> logs = new ArrayList<String>();
logs.add("Robot Initialized");
The Type Parameter
ArrayList<Type> — the type in angle brackets is what kind of object the list holds. ArrayList can only hold objects, never primitives directly — a list of numbers uses the wrapper types Integer/Double (Java auto-converts back and forth, called autoboxing/unboxing):
ArrayList<Double> sensorReadings = new ArrayList<Double>();
sensorReadings.add(2.4); // autoboxed into a Double automatically
Core Methods
ArrayList<String> logs = new ArrayList<String>();
logs.size(); // number of elements (like length, but a method — () required)
logs.add("started"); // appends to the end
logs.add(0, "boot"); // inserts at index 0, shifting everything else right
logs.get(0); // reads the element at index 0
logs.set(0, "ready"); // replaces the element at index 0
logs.remove(0); // removes the element at index 0, shifting later ones left
ArrayList uses methods (get/set) instead of [] — it's a real class, not a built-in language feature the way arrays are.
Array vs. ArrayList, Side by Side
| Operation | array | ArrayList |
|---|---|---|
| count | arr.length | list.size() |
| read | arr[i] | list.get(i) |
| write | arr[i] = v; | list.set(i, v); |
| grow/shrink | not possible | add/remove |
Common Pitfalls
- Using
[]on an ArrayList. It doesn't compile — alwaysget(i)/set(i, v)instead. - Mixing up
.lengthand.size(). Arrays use the field.length;ArrayListuses the method.size(). - Using an uninitialized
ArrayList. DeclaringArrayList<String> list;withoutnew ArrayList<String>()leaves itnull— calling any method on it throwsNullPointerException.
Key Takeaways
ArrayListis a resizable list — use it when the size isn't known up front or will change at runtime.- The type parameter (
ArrayList<Type>) says what it holds; primitives need their wrapper type (Integer,Double). - Core methods:
size(),add(),add(index, obj),get(index),set(index, obj),remove(index). - Arrays use
.lengthand[];ArrayListuses.size()andget/set.
Derived from csawesome-2026: unit-4-data-collections/4.08-arraylist-and-its-methods.md (CSA 4.8)