Core Module
12 min forge

ArrayList in Java

The most commonly used dynamic array implementation.

ArrayList in Java

πŸ“˜ What is it

ArrayList is a resizable-array implementation of the List interface. It grows dynamically as elements are added and allows random access to elements.

⚑ When to use

Use ArrayList when you need frequent access to elements by index and the number of elements can change but removals from the middle are rare.

🧠 Time complexity

  • Access/Get: $O(1)$
  • Add (at end): $O(1)$ (amortized)
  • Add/Remove (at specific index): $O(n)$
  • Search (by value): $O(n)$

πŸ’» Code example

java Standard
import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> cities = new ArrayList<>(); cities.add("New York"); cities.add("London"); cities.get(0); // "New York" cities.size(); // 2 } }

πŸ—οΈ Internal Working

ArrayList is backed by an internal array. When the array is full, it creates a new, larger array (usually 1.5x the old size) and copies all elements to it.

❌ Common mistakes

  • Ignoring Capacity: Not providing an initial capacity when the final size is known (leads to multiple resize operations).
  • Using for removals: Using ArrayList for frequent removals from the beginning or middle (use LinkedList if removals are the primary operation).
  • Concurrent Modification: Modifying an ArrayList while iterating over it with an Iterator or for-each loop incorrectly.