Easy Tutorial
❮ Java Basic Syntax Java8 Nashorn Javascript ❯

Java ArrayList removeRange() Method

Java ArrayList

The removeRange() method is used to delete elements that exist between specified indices.

The syntax for the removeRange() method is:

arraylist.removeRange(int fromIndex, int toIndex)

Note: arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

This method does not return any value.

It only removes a portion of the dynamic array elements, from fromIndex to toIndex-1. This means it does not include the element at the toIndex position.

Note: If fromIndex or toIndex is out of range, or if toIndex < fromIndex, an IndexOutOfBoundsException is thrown.

Example

The following example demonstrates the use of the removeRange() method:

Example

import java.util.*;

class Main extends ArrayList<String> {
    public static void main(String[] args) {
        // Create a dynamic array
        Main sites = new Main();
        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");
        sites.add("Wiki");
        sites.add("Weibo");

        System.out.println("ArrayList : " + sites);

        // Remove elements from index 1 to 3
        sites.removeRange(1, 3);
        System.out.println("ArrayList after removal: " + sites);
    }
}

Executing the above program outputs:

ArrayList : [Google, tutorialpro, Taobao, Wiki, Weibo]
ArrayList after removal: [Google, Wiki, Weibo]

The removeRange() method is protected, so to use it, you need to inherit the ArrayList class. After inheritance, we can use the Main class to create a dynamic array.

The removeRange() method is not commonly used. Instead, you can achieve the same result using the ArrayList subList() and ArrayList clear() methods.

Example

import java.util.ArrayList;

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

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

        // Remove elements from index 1 to 3
        numbers.subList(1, 3).clear();
        System.out.println("Updated ArrayList: " + numbers);
    }
}

Executing the above program outputs:

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

In the above example, we created a dynamic array named numbers.

Note the expression:

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

Java ArrayList

❮ Java Basic Syntax Java8 Nashorn Javascript ❯