.removeRange()
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 theArrayList
.toIndex
: It is the ending index of the element in the range that is to be removed from theArrayList
.
Note:
fromIndex
andtoIndex
are both inclusive in the elements removed from theArrayList
.
Example
import java.util.ArrayList;// Extend the class to arraylist because removeRange() is a protected methodpublic 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 ArrayListtasksList.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 differencesSystem.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]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.