How to add an element at the beginning of an ArrayList in Java
Codemia Knowledge Hub ·
Call list.add(0, element). The add(int index, E element) method inserts element at position index, so index 0 puts it first. Plain add(element) appends to the end.
Why inserting at index 0 is O(n)
An ArrayList (in java.util) is a dynamic array that grows as needed, unlike a fixed-length Java array. That makes it useful when the amount of data is not known until runtime. It is designed for fast access to elements and for adding mainly at the end, which is why inserting at the beginning, or at any arbitrary index, is less straightforward than appending.
To insert at index 0, it has to shift every existing element one position to the right. That takes O(n) time, where n is the number of elements, so frequent insertions at the front can be costly in terms of performance. Inserting at the beginning looks simple, but it is worth understanding this cost before you do it in a loop or on a large list.
Alternatives for frequent front insertions
If you add and remove at the beginning of a list often, consider another data structure. A LinkedList adds and removes at the beginning in O(1) time.
If you need an ArrayList for other reasons, such as random access speed, you can reduce the cost by:
- Sizing the
ArrayListup front to the maximum expected number of elements, which minimizes resizing. - Collecting the elements to add in a temporary structure and combining it with the original list in a single operation, when you have several insertions at once.
| Consideration | Detail |
| Method Used | add(int index, E element) |
| Time Complexity | O(n) |
| Performance | Less efficient for frequent use due to element shifting |
| Alternatives | Consider using LinkedList for frequent additions/removals at the beginning. |
Related reading
- Java associative-array
- Java Byte Array to String to Byte Array
- Java Class that implements Map and keeps insertion order?
- Java convert a byte array to a hex string?
- Java ArrayList replace at specific index
- Java Async Data Load with progress and Threadding nightmares
- Java convert List<String> to a join()d String
- Java, find intersection of two arrays
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.