ArrayList & Collections Basics
Prerequisites: Packages & imports
Unlike a plain array, ArrayList can grow and shrink — it's the
everyday go-to when you don't know the size up front.
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
System.out.println(names.get(0)); // Ada
System.out.println(names.size()); // 2
names.remove("Ada");
for (String name : names) {
System.out.println(name);
}
The <String> is a generic type parameter — it tells the compiler
this list only ever holds Strings, so names.get(0) is already
known to be a String with no cast needed (covered fully in
Generics, in Level 2).
Common mistakes
- Using a raw array when the collection's size needs to change at
runtime — reach for
ArrayListinstead. - Calling
.get(index)past the current.size()— throwsIndexOutOfBoundsException.
Practice
Create an ArrayList<Integer>, add the numbers 1, 2, and 3, then
print their sum using a for-each loop.
Show solution
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println(sum); // 6