Java Utility Library

Java Vector - removeRange() Method



The java.util.Vector.removeRange() method is used to remove from the list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. This shifts any succeeding elements to the left (reduces their index). The method reduces the length of the list by (toIndex - fromIndex) elements. If toIndex and fromIndex are equal then the operation has no effect.

Syntax

protected void removeRange(int fromIndex, int toIndex)

Parameters

fromIndex Specify index of first element to be removed.
toIndex Specify index after last element to be removed.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if fromIndex or toIndex is out of range (fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex)

Example:

In the example below, the java.util.Vector.removeRange() method is used to remove a range of elements from the given vector.

import java.util.*;

// extending the class to vector because 
// removeRange() is a protected method 
public class MyClass extends Vector<Integer> {

  public static void main(String[] args) {
    //creating a vector
    MyClass vec = new MyClass();

    //populating vec
    for(int i = 10; i <= 60; i+=10)
      vec.add(i);

    //printing vec
    System.out.println("Before removeRange, vec contains: " + vec);

    //apply removeRange method on vec
    vec.removeRange(2, 4);

    //printing vec
    System.out.println("After removeRange, vec contains: " + vec); 
  }
}

The output of the above code will be:

Before removeRange, vec contains: [10, 20, 30, 40, 50, 60]
After removeRange, vec contains: [10, 20, 50, 60]

❮ Java.util - Vector