Java ArrayList removeRange() Method with Example

In the previous article we have discussed about Java ArrayList replaceAll() Method with Example

In this article we are going to see the use ArrayList removeRange() method along with suitable examples.

Java ArrayList removeRange() Method with Example

removeRange(int fromIndex, int toIndex):

This java.util.ArrayList.removeRange(int fromIndex, int toIndex) method is used to remove elements from the specified range present in the ArrayList.

It does not return anything.

If the range is out of the size of the ArrayList then It throws IndexOutOfBoundsException.

Syntax:

arrayListName.removeRange(int fromIndex, int toIndex)

Where,

  • arrayListName refers to the name of your ArrayList.
  • int fromIndex refers to the start index of the range
  • int toIndex refers to the end index of the range

Let’s see the program to understand it more clearly.

Approach:

  • Create a new ArrayList of type String.
  • Add string elements into the ArrayList using the add() method.
  • Display the ArrayList elements.
  • Now, using the removeRange() method remove all the elements from the specified range present in the ArrayList.
  • Print the remaining elements.

Program:

import java.util.*;

class Main extends ArrayList<String> 
{
    public static void main(String[] args) 
    {
        // Create an ArrayList using Main class
        Main arr1 = new Main();
        // Adding some elements to the ArrayList
        arr1.add("tiger");
        arr1.add("lion");
        arr1.add("bear");
        arr1.add("wolf");
        arr1.add("rhino");
        // Prints the ArrayList elements
        System.out.println("The elements in the ArrayList are: "+arr1);
        // remove the elements from a specified range
        arr1.removeRange(2,4);
        System.out.println("After removing, Size of the ArrayList is: " + arr1.size());
        System.out.println("The new elements in the ArrayList are: "+arr1);
    }
}
Output:

The elements in the ArrayList are: [tiger, lion, bear, wolf, rhino]
After removing, Size of the ArrayList is: 3
The new elements in the ArrayList are: [tiger, lion, rhino]

Note: This removeRange(int fromIndex, int toIndex) is protected. So it can be only accessed within class/package/subclass else it will give error that “removeRange() has protected access in ArrayList“. As Main class inherits ArrayList so arraylist can be created using the Main class.

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: