Step 2 of 6
33% CompleteAdd 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
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.
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.
// Java ArrayList doubles its capacity when fullArrayList<Integer> list = new ArrayList<>();// Initial capacity: 10 (default)// After adding 10 elements, list is fullfor (int i = 0; i < 10; i++) {list.add(i);}// Current capacity: 10, size: 10// Adding 11th element triggers resizinglist.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