Java Utility Library

Java Vector - remove() Method



The java.util.Vector.remove() method is used to remove the element at the specified position in the vector. It shifts any subsequent elements to the left by subtracting one from their indices. Every removal of element results into reducing the vector size by one unless the vector is empty.

Syntax

public E remove(int index)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number of the element which need to be removed from the vector.

Return Value

Returns the removed element of the vector.

Exception

Throws IndexOutOfBoundsException, if the index is out of range (index < 0 || index >= size()).

Example:

In the example below, the java.util.Vector.remove() method is used to remove the element at the specified position in given vector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(40);
    MyVector.add(50);

    //printing vector
    System.out.println("MyVector contains: "+ MyVector);    

    //delete element at index=2
    MyVector.remove(2);

    //printing vector
    System.out.println("MyVector contains: "+ MyVector);  
  }
}

The output of the above code will be:

MyVector contains: [10, 20, 30, 40, 50]
MyVector contains: [10, 20, 40, 50] 

❮ Java.util - Vector