.removeRange()

JAFY10's avatar
Published Sep 15, 2024
Contribute to Docs

The .removeRange() method removes all elements inside a specified range from an instance of the ArrayList class.

Syntax

arrayListInstance.removeRange(int fromIndex, int toIndex);
  • fromIndex: It is the starting index of the element in the range that is to be removed from the ArrayList.
  • toIndex: It is the ending index of the element in the range that is to be removed from the ArrayList.

Note: fromIndex and toIndex are both inclusive in the elements removed from the ArrayList.

Example

import java.util.ArrayList;
// Extend the class to arraylist because removeRange() is a protected method
public class Tasks extends ArrayList<String> {
public static void main(String[] args) {
// Create an ArrayList called tasksList, which will be empty for now.
Tasks tasksList = new Tasks();
// Add tasks to the ArrayList
tasksList.add("Grab lunch");
tasksList.add("Check mail");
tasksList.add("Pick up Sammy");
tasksList.add("Project review");
tasksList.add("Java terms research");
// Print the list with the new elements, before removing them.
System.out.println("Original list: " + tasksList);
// Remove elements from index 0 to index 3. The first 4 elements.
tasksList.removeRange(0, 3);
// Print the list again to see the differences
System.out.println("List with elements removed: " + tasksList);
}
}

The output will look like this:

Original list: [Grab lunch, Check mail, Pick up Sammy, Project review, Java terms research]
List with elements removed: [Project review, Java terms research]

All contributors

Contribute to Docs

Learn Java on Codecademy