Step 2 of 6

33% Complete

Add Operation

Learn how to add elements to an ArrayList

The Add Operation

The add operation inserts an element into an ArrayList. Unlike static arrays, ArrayLists can grow dynamically when new elements are added beyond the current capacity.

When adding an element, the ArrayList performs:

  • Checking if there's available capacity
  • Resizing the internal array if needed (usually doubles capacity)
  • Inserting the element at the specified position
  • Updating the size counter

Adding at the End (Append)

This is the most common operation - adding an element at the end of the ArrayList. Time complexity: O(1) amortized when there's spare capacity, O(n) when resizing is needed.

Array Visualization

Size: 3 | Capacity: 8

[0]
10
[1]
20
[2]
30
[3]
[4]
[5]
[6]
[7]
Occupied
Available Capacity
Add Element at End (Java)
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // [10]
list.add(20); // [10, 20]
list.add(30); // [10, 20, 30]
// When capacity is exceeded, ArrayList automatically resizes

Adding at a Specific Index

You can also insert an element at any position in the ArrayList. This requires shifting elements to the right, making it O(n) time complexity.

Add Element at Index (Java)
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // [10]
list.add(20); // [10, 20]
list.add(30); // [10, 20, 30]
// Insert 15 at index 1 (between 10 and 20)
list.add(1, 15); // [10, 15, 20, 30]
// The element at index 1 (20) and all following elements shift right

Important: Adding at the beginning or middle requires shifting elements, which is inefficient for large lists. O(n) complexity for worst case (adding at index 0).

Dynamic Resizing

When the ArrayList reaches capacity, it automatically creates a larger array and copies all elements.

ArrayList Resizing Behavior
// Java ArrayList doubles its capacity when full
ArrayList<Integer> list = new ArrayList<>();
// Initial capacity: 10 (default)
// After adding 10 elements, list is full
for (int i = 0; i < 10; i++) {
list.add(i);
}
// Current capacity: 10, size: 10
// Adding 11th element triggers resizing
list.add(10);
// New capacity: 20 (doubled), size: 11
// This ensures amortized O(1) insertion at the end

Practice Exercise

Key Takeaways

  • Append (add at end): O(1) amortized time complexity
  • Insert at index: O(n) time complexity due to shifting elements
  • Automatic resizing: ArrayList doubles capacity when needed
  • Best practice: Add at the end when possible for better performance