Java Vector removeRange(int fromIndex,int toIndex) Method Example

The remove(int index)  and removeElementAt(int index) method of java.util.Vector class removes the element at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted downward to have an index one smaller than the value it had previously whereas removeRange(int fromIndex,int toIndex) method removes from the vector all of the elements whose index is between fromIndex inclusive and toIndex exclusive

Signature

public void removeRange(int fromIndex,int toIndex)

This method removes the all elements whose index is between fromIndex and toIndex. The vector will be shortened by performing operation (toIndex-fromIndex), if toIndex==fromIndex then there will be no effect to the vector.

Example

The following example shows the usage of java.util.Vector.removeRange(fromIndex,toIndex) method.

import java.util.Vector;

public class RemoveRangeMethodVectorExample extends Vector 
{
    public static void main(String args[])
    {
        /*
         * Here we need to extend the Vector class as the 
         * removeRange(int fromIndex,int toIndex) method is a protected method
         */
        RemoveRangeMethodVectorExample rm = new RemoveRangeMethodVectorExample();
        
        //Add the element 
        rm.add("Element1");
        rm.add("Element2");
        rm.add("Element3");
        rm.add("Element4");
        rm.add("Element5");
        rm.add("Element6");
        rm.add("Element7");
        rm.add("Element8");
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector before remove**");
        for(String temp:rm)
        {
            System.out.println(temp);
        }
        
        //Remove the elements of the vector
        rm.removeRange(1,3);
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector after remove**");
        for(String temp:rm)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the Vector before remove**
Element1
Element2
Element3
Element4
Element5
Element6
Element7
Element8
**Elements of the Vector after remove**
Element1
Element4
Element5
Element6
Element7
Element8

Leave a Reply

Your email address will not be published. Required fields are marked *