ArrayList
Overview
Standard arrays in Java are fixed-size; if you create an array of 5, you can never put a 6th item in it. `ArrayList` is a dynamic array from the Java Collections Framework. It automatically resizes itself when it gets full. It is the absolute most commonly used data structure in Java because it combines the fast random-access lookup of an array with the infinite flexibility of a dynamic list.
Syntax
Always use the Interface `List` on the left side of the assignment, and the implementation `ArrayList` on the right side. This allows you to swap to a LinkedList later without breaking your code.
// Using Generics <String> to enforce type safety
List<String> names = new ArrayList<>();
// 1. Adding elements (O(1) time mostly)
names.add("Alice");
names.add("Bob");
names.add(1, "Charlie"); // Insert at index 1
// 2. Reading elements (O(1) time)
String firstPerson = names.get(0); // Alice
// 3. Modifying and Removing
names.set(0, "Alicia"); // Replaces index 0
names.remove("Bob"); // Removes by value
names.remove(0); // Removes by index
int size = names.size(); // Get current countBecause resizing requires copying the entire array, inserting elements is *usually* O(1), but occasionally O(N). To optimize performance, if you know you need 10,000 items, initialize it with capacity: `new ArrayList<>(10000)`.
// When you create an ArrayList, it creates a standard array of size 10 secretly.
List<Integer> list = new ArrayList<>();
// When you add the 11th element, it does the following internally:
// 1. Creates a new array of size 15 (1.5x larger)
// 2. Copies the 10 old elements into the new array
// 3. Adds the 11th element
// 4. Throws away the old array for garbage collectionCommon Pitfalls
- Using `ArrayList` for a queue/stack system where you constantly remove the 0th element. Removing index 0 forces the ArrayList to shift every single other element one slot to the left (O(N) time).
- Using primitive types in the generic diamond `ArrayList<int>`. Generics only support Objects, so you must use Wrapper classes `ArrayList<Integer>`.
Interview Tips
- Understand how ArrayList resizes under the hood (creates a 1.5x larger array, copies elements over, drops the old one).
Real-World Example
ArrayLists are used to fetch result sets from databases where the number of rows returned is unknown until the query finishes.
public class DatabaseRepository {
public List<User> fetchActiveUsers() {
// We don't know how many users are active!
List<User> activeUsers = new ArrayList<>();
ResultSet rs = executeQuery("SELECT * FROM users WHERE active=1");
while(rs.next()) {
activeUsers.add(new User(rs.getString("name")));
}
return activeUsers;
}
}