Java ArrayList removeRange()

The syntax of the removeRange() method is:

arraylist.removeRange(int fromIndex, int toIndex)

Here, arraylist is an object of the ArrayList class.


removeRange() Parameters

The removeRange() method takes two parameters.

  • fromIndex - the starting position from where elements are removed
  • toIndex - the ending position up to which elements are removed

removeRange() Return Value

The removeRange() method does not return any values. Rather, it removes a portion of arraylist.

The portion of arraylist contains elements starting at fromIndex and extends up to element at toIndex-1. That is, the element at toIndex is not included.

Note: The method throws IndexOutOfBoundException, if fromIndex or toIndex is out of range or toIndex < fromIndex.


Example 1: Java ArrayList removeRange()

import java.util.*;

class Main extends ArrayList<String> {
    public static void main(String[] args) {
        // create an ArrayList
        Main arraylist = new Main();

        // add some elements to the ArrayList
        arraylist.add("Java");
        arraylist.add("English");
        arraylist.add("Spanish");
        arraylist.add("Python");
        arraylist.add("JavaScript");
        System.out.println("ArrayList: " + arraylist);

        // remove elements between 1 to 3
        arraylist.removeRange(1, 3);
        System.out.println("Updated ArrayList: " + arraylist);
    }
}

Output

ArrayList: [Java, English, Spanish, Python, JavaScript]
Updated ArrayList: [Java, Python, JavaScript]

The removeRange() method is protected. This means it can only be accessed within the class/package/subclass. This is why the Main method extends the ArrayList class in the above example.

Since the Main class inherits all properties of the ArrayList, we can create the arraylist using the Main class.

However, this is not commonly used in Java. Instead, we combine the ArrayList subList() and ArrayList clear() methods.


Example 2: Remove Multiple Elements

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();

        // add elements to the ArrayList
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(6);
        System.out.println("ArrayList: " + numbers);

        // remove element between 1 to 3
        numbers.subList(1, 3).clear();
        System.out.println("Updated ArrayList: " + numbers);
    }
}

Output

ArrayList: [1, 2, 3, 4, 6]
Updated ArrayList: [1, 4, 6]

In the above example, we have created an arraylist named numbers. Notice the line,

numbers.subList(1, 3).clear();

Here,

  • subList(1, 3) - returns elements at index 1 and 2
  • clear() - remove elements returned by subList()

Also Read:

Did you find this article helpful?