Java ArrayList removeRange() Method

Java ArrayList Java ArrayList

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

The syntax of the removeRange() method is:

arraylist.removeRange(int fromIndex, int toIndex)

Note:arraylist is an object of the ArrayList class.

Parameter Details:

  • fromIndex - starting index position, inclusive of the value at that index
  • toIndex - ending index position, exclusive of the value at that index

Return Value

No return value.

This method only removes a portion of the ArrayList elements, specifically from fromIndex to toIndex-1. In other words, it does not include the element at the toIndex position.

Note: If the fromIndex or toIndex index is out of range, or if toIndex < fromIndex, an IndexOutOfBoundException 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 an ArrayList
        Main sites = new Main();
        sites.add("Google");
        sites.add("Example");
        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 produces the following output:

ArrayList : [Google, Example, Taobao, Wiki, Weibo]
删除后的 ArrayList: [Google, Wiki, Weibo]

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

The removeRange() method is not commonly used; we can usually useArrayList subList()andArrayList clear()method to remove elements.

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an Integer ArrayList
        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 at indices 1 to 3
        numbers.subList(1, 3).clear();
        System.out.println("Updated ArrayList: " + numbers);
    }
}

Executing the above program produces the following output:

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

In the above example, we created an ArrayList named numbers.

Note these expressions:

numbers.subList(1, 3).clear();
  • subList(1, 3)- Returns the elements at indices 1 and 2.
  • clear()- Removes the elements returned by subList().

Java ArrayList Java ArrayList

Other Extensions