ArrayList in Java
ArrayList is the most widely used List implementation in Java. Internally it wraps a plain Object array called elementData. When you construct an ArrayList...
How ArrayList Works Internally
ArrayList is the most widely used List implementation in Java. Internally it wraps a plain Object array called elementData. When you construct an ArrayList with no arguments, it starts with an empty array and lazily allocates an initial capacity of 10 on the first add. When elements fill the current capacity, ArrayList creates a new array of 1.5 times the old size (newCapacity = oldCapacity + (oldCapacity >> 1)) and copies all elements over using System.arraycopy.
This resizing strategy keeps amortized insertion at the end O(1) even though individual resize events are O(n). Accessing an element by index runs in true O(1) time because arrays support direct memory addressing. Inserting or deleting in the middle is O(n) because all subsequent elements must shift.
You can tune performance by specifying an initial capacity: new ArrayList<>(1000) avoids repeated resizing when you know the approximate size up front.
Common Operations and Their Costs
The add(E e) method at the tail runs in O(1) amortized time. The add(int index, E element) method at an arbitrary position is O(n) due to shifting. get(int index) is O(1). remove(int index) is O(n) in the worst case (removing from index 0 shifts all elements). contains(Object o) performs a linear scan in O(n).
ArrayList implements RandomAccess, a marker interface that signals to algorithms like Collections.binarySearch that index-based iteration is efficient. When you see code that checks if (list instanceof RandomAccess), it is optimizing traversal strategy based on this marker.
Iterating with a for-each loop or iterator is safe as long as you do not structurally modify the list during iteration. Doing so raises ConcurrentModificationException, enforced by a modCount field that tracks structural changes.
Code Example and Interview Insight
A concise example: ArrayList<String> cities = new ArrayList<>(); cities.add("Paris"); cities.add("Rome"); cities.add(0, "Tokyo"); System.out.println(cities); prints [Tokyo, Paris, Rome]. Inserting at index 0 shifted the original elements.
To convert an ArrayList to an array: String[] arr = cities.toArray(new String[0]); The pattern new String[0] is preferred over new String[cities.size()] because the JVM optimizes the zero-length hint variant. Going the other direction, Arrays.asList(arr) returns a fixed-size List backed by the array, not a true ArrayList, so calling add on it throws UnsupportedOperationException.
A frequent interview question: is ArrayList thread-safe? No. For concurrent use, wrap it with Collections.synchronizedList() or prefer CopyOnWriteArrayList when reads dominate writes. The synchronized wrapper guards individual method calls but not compound operations, so external synchronization is still needed for check-then-act patterns.