Java ArrayList.remove(): Deleting Elements by Index or Value

The ArrayList.remove() method provides two overloads: remove(int index) to delete and return the element at a 0-based position, and remove(Object o) to delete the first occurrence of a matching value and return a boolean.

Related Removal Methods: Because remove(Object) only deletes the first match, use ArrayList.removeAll() to delete every occurrence of a value or collection. To delete a contiguous slice of indices, see ArrayList.removeRange(). To empty the entire list, use ArrayList.clear().

1. Syntax & Overloaded Method Signatures 🔝

Declared in java.util.ArrayList<E>:

 // 1. Removes the element at the specified 0-based position and returns the removed element
public E remove(int index)

 // 2. Removes the first occurrence of the specified element (returns true if found and removed)
public boolean remove(Object o)
Overload Signature Return Type Time Complexity Operational Rule
remove(int index) E O(n) (O(1) at tail) Deletes element at index, shifts subsequent elements left by 1, and returns the removed element.
remove(Object o) boolean O(n) Finds first match via Objects.equals(), shifts tail left by 1, and returns true (or false if absent).

2. Removing an Element by Value: remove(Object o) 🔝

Passing an object reference searches the list from index 0 upward, removes the first matching element, and returns true (which can be tested inside an if-else statement):

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "Python", "HTML"));
System.out.println(languages);  // [Java, PHP, Python, HTML]

if (languages.remove("Python")) {
    System.out.println("Python is removed");
} else {
    System.out.println("Python is NOT removed");
}
System.out.println(languages);  // [Java, PHP, HTML]

Terminal Output:

[Java, PHP, Python, HTML]
Python is removed
[Java, PHP, HTML]

3. Removing an Element by Position: remove(int index) 🔝

Passing an int index deletes the element at that 0-based position and immediately shifts all higher-indexed elements one slot to the left (decrementing their indices by 1). Notice how calling languages.remove(1) twice in a row first removes "PHP" at index 1, and then removes "Python" after it shifts into index 1:

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "Python", "HTML"));
System.out.println("Initial: " + languages);

String removed1 = languages.remove(1);  // Removes "PHP" at index 1 ("Python" shifts to index 1)
System.out.println("Removed '" + removed1 + "' -> " + languages);

String removed2 = languages.remove(1);  // Now removes "Python" at index 1!
System.out.println("Removed '" + removed2 + "' -> " + languages);

Terminal Output:

Initial: [Java, PHP, Python, HTML]
Removed 'PHP' -> [Java, Python, HTML]
Removed 'Python' -> [Java, HTML]

4. Duplicate Elements: Only the First Match Is Removed 🔝

When an element appears multiple times in an ArrayList, remove(Object o) stops at and deletes only the first occurrence:

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "Python", "HTML", "PHP"));
System.out.println("Before: " + languages);

languages.remove("PHP");  // Removes ONLY index 1 ("PHP"); index 4 ("PHP") remains!
System.out.println("After:  " + languages);

Terminal Output:

Before: [Java, PHP, Python, HTML, PHP]
After:  [Java, Python, HTML, PHP]

5. The Classic ArrayList<Integer> Overload Ambiguity Trap 🔝

On an ArrayList<Integer>, passing a primitive int literal like nums.remove(10) does not autobox to Integer—the Java compiler binds exact primitive int to remove(int index)! Wrap the number in Integer.valueOf(10) when you want to delete the value 10:

ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(10, 20, 30));

nums.remove(Integer.valueOf(10));  // SAFE: Calls remove(Object o) and removes value 10
System.out.println("After removing value 10: " + nums);

int popped = nums.remove(0);  // Calls remove(int index) and removes index 0 (20)
System.out.println("Removed index 0 (" + popped + "): " + nums);

Terminal Output:

After removing value 10: [20, 30]
Removed index 0 (20): [30]

6. Comparison: All 5 Ways to Delete Elements from ArrayList 🔝

Selecting the right removal method for single, bulk, or conditional deletion:

Method What It Deletes Complexity & Best Use Case
remove(int index) Single slot at index O(n) shift; O(1) when removing the last element (size() - 1).
remove(Object o) First match of o O(n); deletes at most 1 element.
removeAll(Collection c) All matches in c Deletes every occurrence of any element present in c.
removeIf(Predicate p) All items matching rule Single-pass O(n) bitset compaction (Java 8+).

7. Production Recipe: Conditional Bulk Deletion with removeIf() 🔝

Instead of writing a manual loop to delete elements matching a condition, use Java 8+ removeIf() to filter the backing array in a single linear pass:

public class ConditionalPurge {
    public static void main(String[] args) {
        ArrayList<String> logs = new ArrayList<>(Arrays.asList("OK", "DEBUG:1", "WARN", "DEBUG:2"));
         // Safely removes all matching elements in a single O(n) pass without CME
        logs.removeIf(entry -> entry.startsWith("DEBUG"));
        System.out.println("Filtered logs: " + logs);
    }
}

Terminal Output:

Filtered logs: [OK, WARN]

8. Practical Recipe: O(1) Swap-and-Pop for Unordered Lists 🔝

If element order does not matter (for example, in an active connection or particle pool), you can avoid the O(n) array shift of remove(index) by popping the last element in O(1) time and overwriting slot index via set(index, last):

public class FastUnorderedRemove {
    public static <E> E swapAndPop(ArrayList<E> list, int idx) {
        E last = list.remove(list.size() - 1);
        return (idx < list.size()) ? list.set(idx, last) : last;
    }
    public static void main(String[] args) {
        ArrayList<String> pool = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
        swapAndPop(pool, 1);
        System.out.println("Pool after swapAndPop(1): " + pool);
    }
}

Terminal Output:

Pool after swapAndPop(1): [A, D, C]

9. Common Developer Pitfalls & Traps 🔝

The Forward-Loop Skipping Bug: for (int i = 0; i < list.size(); i++) list.remove(i)

When you call list.remove(i) inside a forward for loop, the element at i + 1 shifts left into slot i, and then i++ increments past it without ever inspecting it! If you must remove by index in a loop, iterate backward from i = list.size() - 1 down to 0, or use removeIf().

Calling list.remove() Inside a For-Each Loop

Calling list.remove(item) inside for (String item : list) modifies modCount outside the iterator and throws a ConcurrentModificationException on the next step. Use Iterator.remove(), ListIterator.remove(), or list.removeIf().

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListRemoveFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "B"));
        if (list.remove("B") && list.equals(Arrays.asList("A", "C", "B"))) {
            System.out.println("Check 1 Passed: remove(Object) deleted first 'B' only.");
        }
        if ("C".equals(list.remove(1)) && list.size() == 2) {
            System.out.println("Check 2 Passed: remove(1) returned 'C' and shifted tail.");
        }
        System.out.println("All ArrayList.remove() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: remove(Object) deleted first 'B' only.
Check 2 Passed: remove(1) returned 'C' and shifted tail.
All ArrayList.remove() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

How do I remove ALL occurrences of a single value like "PHP"?

Call languages.removeAll(Collections.singleton("PHP")) or languages.removeIf("PHP"::equals).

Does ArrayList.remove() shrink the internal backing array capacity?

No. remove() shifts remaining elements left and sets the vacated tail slot to null (for garbage collection), but the backing Object[] array capacity stays unchanged until you call trimToSize().

What happens if I call remove(null)?

Because null matches the reference type Object, list.remove(null) invokes remove(Object o) and removes the first null element in the list.

Why is removing the last element list.remove(list.size() - 1) so fast?

When index == size() - 1, there are zero subsequent elements to shift with System.arraycopy(), so tail removal runs in O(1) constant time.

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