Java ArrayList.removeRange() Method
protected void removeRange(int fromIndex, int toIndex)
The removeRange() method is used to removes all elements within the specified range from a ArrayList object.
It shifts any succeeding elements to the left (reduces their index).
This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)
Package: java.util
Java Platform: Java SE 8
Syntax:
removeRange(int fromIndex, int toIndex)
Parameters:
Name | Description | Type |
---|---|---|
fromIndex | index of first element to be removed | int |
toIndex | index after last element to be removed | int |
Return Value:
This method does not return any value.
Exceptions:
IndexOutOfBoundsException: Thrown if fromIndex or toIndex is out of range (fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex).
Accessibility:
As of JDK 17, ArrayList.removeRange(int, int) is declared as protected. This means it can only be accessed within the same package or by subclasses of ArrayList.
Example: ArrayList.removeRange Method
The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.
import java.util.*;
public class Main extends ArrayList<Integer>{
public static void main(String[] args) {
// create an empty array list
Main arrlist = new Main();
// use add() method to add values in the list
arrlist.add(10);
arrlist.add(12);
arrlist.add(31);
// print the list
System.out.println("The list:" + arrlist);
// removing range of 1st 2 elements
arrlist.removeRange(0,2);
System.out.println("The list after using removeRange:" + arrlist);
}
}
Output:
The list:[10, 12, 31] The list after using removeRange:[31]
Note: Despite being declared as protected, the removeRange() method is accessible within subclasses of ArrayList, allowing for its usage as demonstrated in the provided example.
Previous:addAll(Collection c) Method
Next:removeAll Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-tutorial/arraylist/arraylist_removerange.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics