Java Utility Library

Java ArrayList - removeRange() Method



The java.util.ArrayList.removeRange() method is used to remove from the list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. This shifts any succeeding elements to the left (reduces their index). The method reduces the length of the list by (toIndex - fromIndex) elements. If toIndex and fromIndex are equal then the operation has no effect.

Syntax

protected void removeRange(int fromIndex, int toIndex)

Parameters

fromIndex Specify index of first element to be removed.
toIndex Specify index after last element to be removed.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if fromIndex or toIndex is out of range (fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex)

Example:

In the example below, the java.util.ArrayList.removeRange() method is used to remove a range of elements from the given ArrayList.

import java.util.*;

// extending the class to ArrayList because 
// removeRange() is a protected method 
public class MyClass extends ArrayList<Integer> {

  public static void main(String[] args) {
    //creating an ArrayList
    MyClass ArrList = new MyClass();

    //populating the ArrayList
    for(int i = 10; i <= 60; i+=10)
      ArrList.add(i);

    //printing the ArrayList
    System.out.println("Before removeRange, ArrList contains: " + ArrList);

    //apply removeRange method on the ArrayList
    ArrList.removeRange(2, 4);

    //printing the ArrayList
    System.out.println("After removeRange, ArrList contains: " + ArrList); 
  }
}

The output of the above code will be:

Before removeRange, ArrList contains: [10, 20, 30, 40, 50, 60]
After removeRange, ArrList contains: [10, 20, 50, 60]

❮ Java.util - ArrayList