ArrayList
Overview
The ArrayList is the most commonly used data structure in Java, and it solves the primary limitation of standard arrays: fixed size. Once you create an array to hold 5 elements, it can never grow. An ArrayList, on the other hand, is a dynamically resizing ordered collection that automatically grows as you add elements.
Internally, an ArrayList is still backed by a plain int[] array under the hood. When you add elements and the internal array becomes full, it creates a new array roughly 1.5x larger and copies all elements over. This means occasional add operations are O(N), but the amortized cost over many adds is still O(1).
Because ArrayList is part of the Java Collections Framework and works with Generics (using <Type> angle brackets), it is strictly type-safe. You declare ArrayList<String> and the compiler guarantees you can never accidentally add an Integer into it, catching errors at compile time rather than at runtime.
Syntax
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
// 1. Adding Elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add(1, "Mango"); // Insert at index 1
// 2. Accessing Elements
System.out.println(fruits.get(0)); // "Apple"
System.out.println("Size: " + fruits.size()); // 4
// 3. Checking and Searching
System.out.println(fruits.contains("Banana")); // true
System.out.println(fruits.indexOf("Cherry")); // 2
// 4. Removing Elements
fruits.remove("Banana"); // Remove by object value
fruits.remove(0); // Remove by index
// 5. Iterating
for (String fruit : fruits) {
System.out.println(fruit);
}
// 6. Sorting
Collections.sort(fruits);
System.out.println(fruits); // Alphabetical order
// 7. Converting to Array
String[] arr = fruits.toArray(new String[0]);
}
}Common Pitfalls
- Using
remove(int index)vsremove(Object o)ambiguity. If you have anArrayList<Integer>and calllist.remove(5), Java resolves it toremove(int index)— removing the element at position 5 — NOT removing the value 5! To remove by value, you must box it:list.remove(Integer.valueOf(5)). - Modifying an ArrayList while iterating over it with a for-each loop. This will immediately throw a
ConcurrentModificationException. If you need to remove items while iterating, always use anIteratorwithiterator.remove(), or uselist.removeIf(condition)(Java 8+). - Choosing ArrayList when LinkedList would be better. ArrayList is extremely fast for random access (
get(i)is O(1)) but slow for insertions/deletions at the middle (O(N) due to element shifting). If your primary operation is inserting/deleting from the middle,LinkedListoffers O(1) for those operations.
Interview Questions
add(), get(), and remove() in an ArrayList?add() to the end is amortized O(1), but O(N) when a resize occurs. get(index) is O(1) constant time due to direct array indexing. remove(index) from the middle is O(N) because all elements after it must be shifted one position to the left.
The default initial capacity is 10. When you add an 11th element, Java creates a new internal array with capacity ≈ 15 (1.5× growth), copies all 10 existing elements, then adds the new element. This is why pre-sizing with new ArrayList<>(expectedSize) can significantly improve performance in bulk-loading scenarios.
ArrayList and Vector?Vector is the legacy (Java 1.0) predecessor to ArrayList. Both are dynamically resizing array-backed lists. The key difference is that all Vector methods are synchronized, making it thread-safe but significantly slower. ArrayList is not synchronized but is far faster in single-threaded contexts. Use Collections.synchronizedList(new ArrayList<>()) for thread-safe ArrayList.
Real-World Example
Almost every backend API returns data as a list. When a product catalog query hits the database, the JDBC result set is iterated and each Product object is added to an ArrayList<Product>. This list is then serialized to JSON and returned in the HTTP response.
public List<Product> getProductsByCategory(String category) {
ArrayList<Product> products = new ArrayList<>();
ResultSet rs = db.query("SELECT * FROM products WHERE category=?", category);
while (rs.next()) {
products.add(new Product(
rs.getString("name"),
rs.getDouble("price")
));
}
return products; // Serialized to JSON by Spring
}Check Your Knowledge
Test your understanding of ArrayList with these quick questions.