Java ArrayList.add(): Appending & Inserting Elements

The ArrayList.add() method provides two overloads: add(E e) to append an element to the end of the list in amortized O(1) time, and add(int index, E element) to insert an element at a specific 0-based position.

Related List Operations: To append an entire collection at once, use ArrayList.addAll(). To overwrite an existing element at an index without shifting, use ArrayList.set(). To pre-allocate backing capacity before a large loop, see ArrayList.ensureCapacity().

1. Syntax & Overloaded Method Signatures 🔝

Defined in java.util.ArrayList<E> (implementing java.util.List<E>):

 // 1. Append element to the end of the list (returns true)
public boolean add(E e)

 // 2. Insert element at the specified 0-based index (shifts subsequent elements right)
public void add(int index, E element)
Overload Signature Return Type Time Complexity Behavior & Operational Rule
add(E e) boolean Amortized O(1) Appends e to the end of the list and always returns true.
add(int index, E e) void O(n) Inserts e at index, shifting elements at index..size-1 one slot right.

2. Appending Elements at the End with add(E e) 🔝

The single-argument add(E e) places each new item at the tail of the ArrayList and returns true (which can be checked inside an if-else condition as defined by the Collection.add() contract):

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
languages.add("HTML");

if (languages.add("C++")) {
    System.out.println("Successfully added C++");
}
System.out.println(languages);

Terminal Output:

Successfully added C++
[Java, PHP, Python, HTML, C++]

3. Positional Insertion with add(int index, E element) 🔝

Passing an explicit 0-based index inserts the element at that position and shifts existing elements from index onward to the right (incrementing their indices by 1). Passing index == list.size() is valid and appends to the end:

ArrayList<String> queue = new ArrayList<>();
queue.add("Task-B");
queue.add("Task-C");

queue.add(0, "Task-A");           // Insert at head (index 0)
queue.add(2, "Task-B-Urgent");    // Insert in middle (index 2)
queue.add(queue.size(), "End");   // Insert at tail (index == size())

System.out.println(queue);

Terminal Output:

[Task-A, Task-B, Task-B-Urgent, Task-C, End]

4. Duplicate Elements, Null References & Autoboxing 🔝

Unlike mathematical sets, ArrayList allows duplicate values and multiple null elements. Primitive values (such as int) are automatically boxed into wrapper objects (Integer) when added:

ArrayList<Integer> scores = new ArrayList<>();
scores.add(95);      // Autoboxed to Integer.valueOf(95)
scores.add(95);      // Duplicates are permitted
scores.add(null);    // null elements are permitted
System.out.println("Scores: " + scores + " | Size: " + scores.size());

Terminal Output:

Scores: [95, 95, null] | Size: 3

5. Exception Handling: IndexOutOfBoundsException 🔝

For add(int index, E element), the valid range of index is 0 <= index <= size() (measured via ArrayList.size()). Any negative index or index strictly greater than size() throws an IndexOutOfBoundsException:

ArrayList<String> items = new ArrayList<>();
items.add("Alpha");  // size is 1 (valid insert indices: 0 or 1)

try {
    items.add(3, "Omega");  // Invalid: index 3 > size 1
} catch (IndexOutOfBoundsException ex) {
    System.out.println("Caught: " + ex.getMessage());
}

Terminal Output:

Caught: Index: 3, Size: 1

6. Comparison: add() vs set() vs addAll() 🔝

Choosing the right mutation method on ArrayList:

Method Changes Size? Valid Index Range Primary Use Case
add(E e) Yes (+1) Appends at size() Fast tail insertion in amortized O(1).
add(int i, E e) Yes (+1) 0 <= i <= size() Splicing a single element at index i.
set(int i, E e) No (0) 0 <= i < size() Replacing an existing element in O(1).
addAll(Collection) Yes (+k) Tail or 0 <= i <= size() Bulk-inserting multiple elements in a single copy.

7. Production Recipe: Maintaining a Sorted List with Binary Search 🔝

Combining Collections.binarySearch() with add(int index, E element) to insert items directly into their sorted order:

import java.util.ArrayList;
import java.util.Collections;

public class SortedListInsert {
    public static void insertSorted(ArrayList<Integer> list, int val) {
        int idx = Collections.binarySearch(list, val);
        if (idx < 0) idx = -(idx + 1);  // Compute insertion point
        list.add(idx, val);
    }
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>();
        insertSorted(nums, 30);
        insertSorted(nums, 10);
        insertSorted(nums, 20);
        System.out.println("Sorted: " + nums);
    }
}

Terminal Output:

Sorted: [10, 20, 30]

8. Practical Recipe: Pre-Sizing with ensureCapacity() Before Loops 🔝

By default, an ArrayList starts with capacity 10 and grows by 50% whenever full. Calling ensureCapacity(n) before a loop of add() calls allocates the backing array once:

import java.util.ArrayList;

public class PreSizedBatchAdd {
    public static void main(String[] args) {
        ArrayList<Integer> ids = new ArrayList<>();
        ids.ensureCapacity(5);  // Avoid internal array reallocation copies
        for (int i = 101; i <= 105; i++) {
            ids.add(i);
        }
        System.out.println("Batch IDs: " + ids);
    }
}

Terminal Output:

Batch IDs: [101, 102, 103, 104, 105]

9. Common Developer Pitfalls & Traps 🔝

Calling add() Inside a For-Each Loop Throws ConcurrentModificationException

Mutating an ArrayList via list.add() while iterating over it with an enhanced for (E item : list) loop increments modCount and immediately throws ConcurrentModificationException. Use ListIterator.add() or collect new items in a separate list and call addAll() afterward.

Repeatedly Calling add(0, element) on Large Lists

Inserting at index 0 shifts every existing element via System.arraycopy() in O(n) time. Doing this n times in a loop degrades to O(n^2) time. Use ArrayDeque.addFirst() if you need frequent front insertions.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

import java.util.ArrayList;

public class ArrayListAddFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        if (list.add("First") && list.add("Third")) {
            System.out.println("Check 1 Passed: Tail append returned true.");
        }
        list.add(1, "Second");
        if (list.get(1).equals("Second") && list.get(2).equals("Third")) {
            System.out.println("Check 2 Passed: Positional add shifted elements right.");
        }
        System.out.println("Final List: " + list);
    }
}

Terminal Output:

Check 1 Passed: Tail append returned true.
Check 2 Passed: Positional add shifted elements right.
Final List: [First, Second, Third]

11. Frequently Asked Questions (FAQ) 🔝

Can ArrayList.add(E e) ever return false?

No. Unlike Set.add() (which returns false on duplicates), ArrayList.add(E e) always permits duplicates and always returns true (unless an OutOfMemoryError is thrown).

What is the difference between add(index, e) and set(index, e)?

add(index, e) inserts a new element and increases size() by 1, whereas set(index, e) overwrites the existing element at index without changing the list size.

Can I call add(5, "X") on an empty ArrayList?

No. Even if you pre-allocated capacity with new ArrayList<>(10), the logical size() is still 0, so add(5, "X") throws IndexOutOfBoundsException.

Is ArrayList.add() thread-safe?

No. Concurrent calls to add() from multiple threads without synchronization can corrupt the internal array or lose elements. Wrap the list with Collections.synchronizedList() or use CopyOnWriteArrayList.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer