Java ArrayList.removeRange(): Deleting an Index Slice in One Shift

The ArrayList.removeRange(int fromIndex, int toIndex) method removes all elements whose index is between fromIndex (inclusive) and toIndex (exclusive), shifting all subsequent elements left in a single memory copy.

Protected Access & Public Idiom: Because removeRange() is declared protected, normal caller code invokes it via list.subList(fromIndex, toIndex).clear(). For single-element deletion, see ArrayList.remove(); for value-based bulk deletion, see ArrayList.removeAll().

1. Syntax, Protected Visibility & Half-Open Range Rule 🔝

Declared in java.util.ArrayList<E> (overriding AbstractList.removeRange):

 // Protected method in java.util.ArrayList (fromIndex inclusive, toIndex exclusive)
protected void removeRange(int fromIndex, int toIndex)

 // Standard public idiom that calls removeRange(fromIndex, toIndex) internally:
list.subList(fromIndex, toIndex).clear();
Parameter / Aspect Type / Rule Operational Description
fromIndex int (Inclusive) 0-based index of the first element to be removed.
toIndex int (Exclusive) Index immediately after the last element to be removed (removes toIndex - fromIndex items).
Visibility protected void Directly callable only inside subclasses of ArrayList; public callers use subList(a, b).clear().

2. Calling removeRange(1, 3) via an ArrayList Subclass 🔝

When a class extends ArrayList<String>, it inherits protected access and can call removeRange(1, 3) directly to delete indices 1 ("One") and 2 ("Two"):

public class CustomList extends ArrayList<String> {
    public static void main(String[] args) {
        CustomList languages = new CustomList();
        languages.addAll(Arrays.asList("Zero", "One", "Two", "Three", "Four", "Five"));
        System.out.println("Before: " + languages);

        languages.removeRange(1, 3);
        System.out.println("After:  " + languages);
    }
}

Terminal Output:

Before: [Zero, One, Two, Three, Four, Five]
After:  [Zero, Three, Four, Five]

3. The Standard Public Idiom: list.subList(1, 3).clear() 🔝

In everyday application code, you should not subclass ArrayList just to delete a range. Instead, call languages.subList(1, 3).clear(), which is public and delegates directly to ArrayList.removeRange(1, 3) under the hood:

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Zero", "One", "Two", "Three", "Four", "Five")
);

languages.subList(1, 3).clear();
System.out.println("After subList(1, 3).clear(): " + languages);

Terminal Output:

After subList(1, 3).clear(): [Zero, Three, Four, Five]

4. Boundary Rules: Empty Range No-Op & IndexOutOfBoundsException 🔝

When fromIndex == toIndex, removeRange() safely does nothing. If fromIndex < 0, toIndex > size(), or fromIndex > toIndex, an IndexOutOfBoundsException (or IllegalArgumentException on subList) is thrown:

ArrayList<String> items = new ArrayList<>(Arrays.asList("A", "B", "C"));

 // 1. Equal indices (fromIndex == toIndex) is a safe no-op:
items.subList(1, 1).clear();
System.out.println("After (1, 1) no-op: " + items);

 // 2. Invalid range (fromIndex > toIndex or out of bounds) throws exception:
try {
    items.subList(0, 5).clear();
} catch (IndexOutOfBoundsException ex) {
    System.out.println("Caught out-of-bounds: " + ex.getMessage());
}

Terminal Output:

After (1, 1) no-op: [A, B, C]
Caught out-of-bounds: toIndex = 5

5. Why removeRange() / subList().clear() Beats a Loop of remove() 🔝

Deleting k contiguous elements by calling list.remove(fromIndex) in a loop shifts the tail of the array k separate times (O(k * n) time). removeRange() shifts the tail once by k positions via a single System.arraycopy() call and nulls out the k vacated tail slots for garbage collection:

 // subList(1, 4).clear() invokes removeRange(1, 4) -> 1 single System.arraycopy!
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
nums.subList(1, 4).clear();
System.out.println("Single-shift result: " + nums);

Terminal Output:

Single-shift result: [10, 50]

6. Comparison: Ways to Delete Multiple Elements by Index 🔝

Choosing the right range deletion approach in Java:

Idiom Array Shifts Visibility & Recommendation
list.subList(from, to).clear() 1 shift (O(n)) Best practice for all public List and ArrayList code.
subclass.removeRange(from, to) 1 shift (O(n)) protected hook; only used inside custom List implementations.
Loop of list.remove(from) k shifts (O(k*n)) Avoid for large ranges due to repeated array copying.

7. Production Recipe: Sliding Window Log Buffer 🔝

Evicting the oldest entries from the front of an in-memory log buffer in a single shift when it exceeds maxKeep:

public class SlidingLogWindow {
    public static void main(String[] args) {
        ArrayList<String> logs = new ArrayList<>(Arrays.asList("E1", "E2", "E3", "E4", "E5"));
        int maxKeep = 3;
        if (logs.size() > maxKeep) {
             // Drop oldest entries at the front in a single shift
            logs.subList(0, logs.size() - maxKeep).clear();
        }
        System.out.println("Recent logs: " + logs);
    }
}

Terminal Output:

Recent logs: [E3, E4, E5]

8. Practical Recipe: Truncating a List to Top-N Results 🔝

When removing the tail of a list from maxSize to list.size(), subList(maxSize, list.size()).clear() requires zero element shifting and simply nulls out the trailing slots:

public class TruncateTail {
    public static void main(String[] args) {
        ArrayList<String> top = new ArrayList<>(Arrays.asList("Gold", "Silver", "Bronze", "4th", "5th"));
        if (top.size() > 3) top.subList(3, top.size()).clear();
        System.out.println("Top 3 podium: " + top);
    }
}

Terminal Output:

Top 3 podium: [Gold, Silver, Bronze]

9. Common Developer Pitfalls & Traps 🔝

Compiler Error: removeRange(int,int) has protected access in java.util.ArrayList

If you write ArrayList<String> list = new ArrayList<>(); list.removeRange(1, 3); inside an ordinary class, javac rejects it because removeRange is protected. Replace that line with list.subList(1, 3).clear();.

Forgetting That toIndex Is Exclusive

removeRange(1, 3) removes 3 - 1 = 2 elements (indices 1 and 2), not index 3. To include the last element of the list, pass list.size() as toIndex.

10. Complete Compilable Java Program 🔝

Compile and run this verification class demonstrating both subclass removeRange() and public subList().clear():

public class ArrayListRemoveRangeFullDemo extends ArrayList<Integer> {
    public static void main(String[] args) {
        ArrayListRemoveRangeFullDemo list = new ArrayListRemoveRangeFullDemo();
        list.addAll(Arrays.asList(0, 1, 2, 3, 4, 5));
        list.removeRange(2, 5);  // Removes indices 2, 3, 4
        if (list.equals(Arrays.asList(0, 1, 5))) {
            System.out.println("Check 1 Passed: removeRange(2, 5) left [0, 1, 5].");
        }
        list.subList(0, 2).clear();  // Removes indices 0, 1
        if (list.equals(Arrays.asList(5))) {
            System.out.println("Check 2 Passed: subList(0, 2).clear() left [5].");
        }
        System.out.println("All ArrayList.removeRange() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: removeRange(2, 5) left [0, 1, 5].
Check 2 Passed: subList(0, 2).clear() left [5].
All ArrayList.removeRange() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Why did the Java designers make ArrayList.removeRange() protected?

removeRange() is an internal SPI hook defined by AbstractList so that calling list.subList(from, to).clear() on any List can automatically take advantage of fast bulk array shifting without cluttering the public List interface with duplicate methods.

How many elements are removed by removeRange(fromIndex, toIndex)?

Exactly toIndex - fromIndex elements are removed, decreasing size() by toIndex - fromIndex.

Does subList(0, list.size()).clear() do the same thing as list.clear()?

Yes, both remove all elements in O(n) time, though calling list.clear() directly is simpler when emptying the entire list.

Can I keep using a subList variable after calling clear() on it?

Yes, if you call clear() on the subList itself, that subList view remains valid (now with size 0). However, mutating the parent ArrayList directly afterward invalidates any older subList views.

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