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

OperationarrayArrayList
countarr.lengthlist.size()
readarr[i]list.get(i)
writearr[i] = v;list.set(i, v);
grow/shrinknot possibleadd/remove

Common Pitfalls

  • Using [] on an ArrayList. It doesn't compile — always get(i)/set(i, v) instead.
  • Mixing up .length and .size(). Arrays use the field .length; ArrayList uses the method .size().
  • Using an uninitialized ArrayList. Declaring ArrayList<String> list; without new ArrayList<String>() leaves it null — calling any method on it throws NullPointerException.

Key Takeaways

  • ArrayList is 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 .length and []; ArrayList uses .size() and get/set.

Derived from csawesome-2026: unit-4-data-collections/4.08-arraylist-and-its-methods.md (CSA 4.8)