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 Standardimport 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
ArrayListfor frequent removals from the beginning or middle (useLinkedListif removals are the primary operation). - Concurrent Modification: Modifying an
ArrayListwhile iterating over it with anIteratororfor-eachloop incorrectly.