Java
ArrayList
Programming
Data Structures
Coding Tips

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.

java
1import java.util.ArrayList;
2
3public class Main {
4    public static void main(String[] args) {
5        ArrayList<String> list = new ArrayList<>();
6        list.add("B"); // Adding element normally
7        list.add(0, "A"); // Adding element at the first position
8        System.out.println(list); // Output: [A, B]
9    }
10}

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 ArrayList up 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.
ConsiderationDetail
Method Usedadd(int index, E element)
Time ComplexityO(n)
PerformanceLess efficient for frequent use due to element shifting
AlternativesConsider using LinkedList for frequent additions/removals at the beginning.

Course
Intermediate
27 lessons
15 hours
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 course
Data 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.

Practice algorithms