ArrayList is a resizable array — the everyday replacement for int[]
when the size isn't known up front.
import java.util.ArrayList;
import java.util.List;
List<String> books = new ArrayList<>();
books.add("Muna Madan");
books.add("Palpasa Cafe");
books.add(0, "Seto Dharti"); // insert at index
System.out.println(books.get(1)); // Muna Madan
System.out.println(books.size()); // 3
System.out.println(books.contains("Palpasa Cafe")); // true
System.out.println(books.indexOf("Muna Madan")); // 1
books.set(1, "Radha"); // replace
books.remove("Radha"); // by value
books.remove(0); // by index
books.clear();
System.out.println(books.isEmpty()); // trueNote List<String> books = new ArrayList<>() — declare the interface
on the left, the implementation on the right. Swapping to LinkedList
later then touches one line.
Generics
The <String> is a type parameter: it tells the compiler what the list
holds, so mistakes are caught at compile time and no casting is needed.
List<Integer> nums = new ArrayList<>();
nums.add(42);
// nums.add("hello"); ← compile error, and that's a good thing
int n = nums.get(0); // no cast requiredCollections cannot hold primitives — use the wrapper types (Integer,
Double).
Iterating
for (String b : books) {
System.out.println(b);
}
books.forEach(System.out::println);Removing while iterating
Removing inside a for-each throws ConcurrentModificationException. Use
removeIf:
books.removeIf(b -> b.startsWith("A"));Immutable lists
List<String> fixed = List.of("a", "b", "c");
// fixed.add("d"); ← UnsupportedOperationExceptionList.of() is perfect for constants and method arguments. Wrap it in
new ArrayList<>(List.of(...)) when you need a mutable copy.
Sorting
List<String> names = new ArrayList<>(List.of("Ram", "Sita", "Hari"));
Collections.sort(names); // natural order
names.sort(Comparator.reverseOrder());
names.sort(Comparator.comparing(String::length));ArrayList vs LinkedList
ArrayList is fast for random access (get(i)) and is the right default.
LinkedList is faster only for frequent insertion/removal at the front.
In practice, use ArrayList unless profiling says otherwise.