ArrayList removeRange(int fromIndex int toIndex) method in java

Let’s learn ArrayList removeRange(int fromIndex int toIndex) method in java.

ArrayList removeRange(int fromIndex int toIndex) method in java

removeRange(int fromIndex, int toIndex) method of ArrayList class removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.

Syntax:

protected void removeRange(int fromIndex, int toIndex)

Parameters:

fromIndex index of first element to be removed.

toIndex index after last element to be removed.

Throws:

IndexOutOfBoundsException – if fromIndex or toIndex is out of range(fromIndex < 0 ||toIndex > size() ||toIndex < fromIndex).

Also read – ArrayList in java

Now let’s see example on ArrayList removeRange(int fromIndex, int toIndex) method.

import java.util.ArrayList;
// extending class since removeRange() is a protected method
public class ArrayListRemoveRangeMethodExample extends ArrayList<Integer>
{
   public static void main(String[] args)
   {
      ArrayListRemoveRangeMethodExample al = new ArrayListRemoveRangeMethodExample();
      al.add(23);
      al.add(38);
      al.add(18);
      al.add(62);
      al.add(27);
      al.add(95);
      System.out.println("ArrayList before using removeRange method: " + al);
      // removing range of first 2 elements
      al.removeRange(0, 2);
      System.out.println("ArrayList after using removeRange method: " + al);
   }
}


Output:

ArrayList before using removeRange method: [23, 38, 18, 62, 27, 95]
ArrayList after using removeRange method: [18, 62, 27, 95]