Java Arraylist Removerange
# Java ArrayList removeRange() Method
[ Java ArrayList](#)
The removeRange() method is used to remove the elements between the 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:**
* fromIndex - The starting index position, including the value at this index position.
* toIndex - The ending index position, excluding the value at this index position.
### Return Value
It returns no value.
This method only removes a part of the dynamic array elements, from fromIndex to toIndex-1. That is, it does not include the element at the toIndex index position.
Note: If the fromIndex or toIndex index 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{
public static void main(String[] args){
// Create a dynamic array
Main sites =new Main();
sites.add("Google");
sites.add("");
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);
}
}
The output of executing the above program is:
ArrayList : [Google, , 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. We can usually use the [ArrayList subList()](#) and [ArrayList clear()](#) methods to achieve element removal.
## Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create an integer dynamic array
ArrayList 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 index positions 1 to 3
numbers.subList(1, 3).clear();
System.out.println("Updated ArrayList: "+ numbers);
}
}
The output of executing the above program is:
ArrayList: [1, 2, 3, 4, 6]Updated ArrayList: [1, 4, 6]
In the above example, we created a dynamic array named numbers.
Note these expressions:
numbers.subList(1, 3).clear();
* **subList(1, 3)** - Returns the elements at index values 1 and 2.
* **clear()** - Removes the elements returned by subList().
[ Java ArrayList](#)
YouTip