English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList removeRange() method deletes elements from the ArrayList between specified indices.
The syntax of removeRange() method is:
arraylist.removeRange(int fromIndex, int toIndex)
removeRange() method has two parameters.
fromIndex -The starting position of the element to be deleted from
toIndex - The end position of the element to be deleted
The removeRange() method does not return any value. Instead, it deletes a part of the arraylist
A part of arraylist starting from fromIndex includes elements up to toIndex-1of the elements. That is, it does not include the element at toIndex
Note: If fromIndex or toIndex is out of range, or toIndex < fromIndex, the method throws an IndexOutOfBoundsException.
import java.util.*; class Main extends ArrayList<String> { public static void main(String[] args) { //Create an ArrayList Main arraylist = new Main(); //Add elements to the ArrayList arraylist.add("Java"); arraylist.add("English"); arraylist.add("Spanish"); arraylist.add("Python"); arraylist.add("JavaScript"); System.out.println("ArrayList: ") + arraylist); //delete1to3between elements arraylist.removeRange(1, 3); System.out.println("Updated ArrayList: ") + arraylist); } }
Output Result
ArrayList: [Java, English, Spanish, Python, JavaScript] Updated ArrayList: [Java, Python, JavaScript]
The removeRange() method uses the access modifier protected. This means it can only beclass / package / subclass (subclass)Access it. This is why the Main method in the above example inherits the ArrayList class.
Since the Main class inherits all properties of ArrayList, we can use the Main class to create an arraylist.
However, this is not commonly used in Java. Instead, we useArrayList subList()andArrayList clear()Method.
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); //delete1to3between elements numbers.subList(1, 3).clear(); System.out.println("Updated ArrayList: ") + numbers); } }
Output Result
ArrayList: [1, 2, 3, 4, 6] Updated ArrayList: [1, 4, 6]
In the above example, we created an array list named numbers. Note this line,
numbers.subList(1, 3).clear();
Here,
subList(1, 3) - return index1and2ofelements
clear() - Delete elements returned by subList()