Javac · Java Tutorials - ArrayList removeRange Method Tutorial

ArrayList removeRange Method Tutorial

protected void removeRange(int fromIndex, int toIndex)

The removeRange method removes all records beginning at the fromIndex all the way up to, but not including the element at toIndex. The removeRange method is the strangest method in ArrayList class. I say this because it has the protected access modifier applied. That means that we cannot invoke this method on an instance of an ArrayList because our class is not part of the java.util package. Seems very strange to me, but there is a way we can get around this limitation. There is also a little more to this anomaly that I'll explain in the video.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md ArrayListRemoveRange
C:\Java>cd ArrayListRemoveRange
C:\Java\ArrayListRemoveRange>Notepad ArrayListRemoveRange.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.util.*;
class ArrayListRemoveRange {
    public static void main(String args[]) {
        ArrayList<String> states = new ArrayList<String>();
        Collections.addAll(states, "Alaska", "Alabama", "Alabama", "California", "Colorado", "Hawaii", "New York");
        System.out.println("states = " + states);
    
        states.removeRange(0, 3); // error
        //System.out.println("states.removeRange(0, 3), states = " + states);
        //states.subList(0, 3).clear();
        //System.out.println("states.subList(0, 3).clear(), states = " + states);	
    }
}

Now switch back to the command prompt (CMD) and type in javac ArrayListRemoveRange.java and press Enter.
Now type in java ArrayListRemoveRange and press Enter.


C:\Java\ArrayListRemoveRange>javac ArrayListRemoveRange.java
C:\Java\ArrayListRemoveRange>java ArrayListRemoveRange
states = [Alaska, Alabama, Alabama, California, Colorado, Hawaii, New York]
states.removeRange(0, 3), states = [California, Colorado, Hawaii, New York]


Final thoughts

I am not entirely sure why this method is protected, but just keep in mind the workaround if you ever have the need to use such a feature.


Tutorials