Vector removeElementAt(int index) method java

Let’s learn vector removeElementAt(int index) method in java.

Vector removeElementAt(int index) method in java

removeElementAt(int index) method deletes the component 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.

The size of this vector is decreased by 1. The index must be a value greater than or equal to 0 and less than the current size of the vector.

Syntax

public void removeElementAt(int index)

Parameters

index the index of the object to remove

Throws

ArrayIndexOutOfBoundsException – if the index is out of range(index < 0 || index >= size())

Example

import java.util.*;

class VectorRemoveElementAtDemo
{
   public static void main(String[] args) 
   {
      Vector<Integer> v = new Vector<Integer>();
      v.add(11);
      v.add(12);
      v.add(13);
      v.add(14);
      v.add(15);
      System.out.println("Vector elements before removeElementAt() method : " + v);
      System.out.println("Removing element at index 2 : ");
      v.removeElementAt(2);
      System.out.println("Vector elements after removeElementAt() method : " + v);
   }
}

Output:

Vector elements before removeElementAt() method : [11, 12, 13, 14, 15]
Removing element at index 2 :
Vector elements after removeElementAt() method : [11, 12, 14, 15]


If the index is out of range removeElementAt(int index) method throws ArrayIndexOutOfBoundsException.

import java.util.*;

class VectorRemoveElementAtDemo
{
   public static void main(String[] args) 
   {
      Vector<Integer> v = new Vector<Integer>();
      v.add(11);
      v.add(12);
      v.add(13);
      v.add(14);
      v.add(15);
      System.out.println("Vector elements before removeElementAt() method : " + v);
      System.out.println("Removing element at index 2 : ");
      v.removeElementAt(8);
      System.out.println("Vector elements after removeElementAt() method : " + v);
   }
}

Output:

Vector elements before removeElementAt() method : [11, 12, 13, 14, 15]
Removing element at index 2 :
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 8 >= 5
at java.base/java.util.Vector.removeElementAt(Vector.java:549)
at ArraysInJava/com.collections.java.VectorRemoveElementAtDemo.main(VectorRemoveElementAtDemo.java:17)


Also read – ArrayList in java