How to Initialize an ArrayList in Java
The most common way to create an ArrayList in Java is new ArrayList<>() for an empty list, or new ArrayList<>(List.of(...))) to start with values. If the list is read-only, List.of(...) alone is simpler and more efficient.
Empty ArrayList
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
names.add("Linus");
Use the interface type List<String> on the left (not ArrayList<String>) — this makes it easy to swap the implementation later.
ArrayList with initial values
// Mutable list starting with values:
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
numbers.add(6); // works — it's mutable
// Immutable shorthand (can't add/remove):
List<String> days = List.of("Mon", "Tue", "Wed");
// days.add("Thu"); // UnsupportedOperationException!
// Old style (still used, mutable):
List<String> old = new ArrayList<>(Arrays.asList("a", "b", "c"));
Pre-sized ArrayList
// Hint at initial capacity to avoid internal resizing (performance tuning):
List<String> large = new ArrayList<>(10_000);
// Still empty — capacity is not the same as size
The default initial capacity is 10. If you know you will add thousands of elements, passing a larger initial capacity avoids repeated internal array copying.
Copy of an existing list
List<String> original = List.of("a", "b", "c");
List<String> copy = new ArrayList<>(original);
copy.add("d"); // doesn't affect original
Common ArrayList operations
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.add("d"); // append
list.add(1, "z"); // insert at index 1
list.remove("b"); // remove by value
list.remove(0); // remove by index
list.get(0); // read element at index 0
list.set(0, "x"); // replace element at index 0
list.size(); // number of elements
list.contains("c"); // boolean membership test
list.indexOf("c"); // index of first occurrence (-1 if absent)
list.clear(); // remove all elements
list.isEmpty(); // true if size == 0
Iterating
for (String s : list) { System.out.println(s); }
list.forEach(System.out::println); // Java 8+
list.stream().filter(s -> s.length() > 1).forEach(System.out::println); // Stream API