VOOZH about

URL: https://www.geeksforgeeks.org/java/arraylist-removerange-java-examples/

⇱ Arraylist removeRange() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Arraylist removeRange() Method in Java with Examples

Last Updated : 6 Aug, 2025

The removeRange() method of the ArrayList class in Java is used to remove all elements from the list within the specified range of indices. This method removes the elements from the starting index (fromIndex) to the ending index (toIndex).

Example 1: Here, we use the removeRange() method to remove a range of integers from an ArrayList.


Output
[5, 7, 11, 13, 17]
[5, 17]

Syntax of Arraylist removeRange() Method

protected void removeRange(int fromIndex, int toIndex)

Parameters:

  • fromIndex: Starting index from which index elements are to be removed (inclusive).
  • toIndex: The ending index of the range (exclusive).

Returns: This method does not return any value.

Exception: IndexOutOfBoundsException: If the specified range is invalid (ex- fromIndex < 0, toIndex > size, or fromIndex > toIndex).

Example 2: Here, we use the removeRange() method to remove a range of strings from an ArrayList.


Output
Original List: [Sweta, Gudly, Amiya, Ankita, Eva]
Updated List: [Sweta, Gudly, Eva]

Example 3: In this example, an error caused when the removeRange() method is used with an invalid range (where the ending index is out of bounds).

Output:

Hangup (SIGHUP)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: length -1 is negative
at java.base/java.lang.System.arraycopy(Native Method)
at java.base/java.util.ArrayList.shiftTailOverGap(ArrayList.java:778)
at java.base/java.util.ArrayList.removeRange(ArrayList.java:773)
at GFG.main(GFG.java:22)

Explanation: In the above example, the method removeRange(1, 4) is trying to remove elements from index 1 to 4. But the valid indices are 0, 1, and 2 (the list has only 3 elements), the range is invalid that cause an IndexOutOfBoundsException to be thrown.

Note: This method is protected and is used within subclasses of ArrayList or through custom implementations.

Comment