Removing Single Elements in a Vector in Java


A single element in the Vector can be removed using the java.util.Vector.remove() method. This method removes the element at the specified index in the Vector. It returns the element that was removed. Also after the element is removed from the specified index, the rest of the Vector elements are shifted to the left.

A program that demonstrates this is given as follows:

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector(5);
      vec.add(4);
      vec.add(1);
      vec.add(6);
      vec.add(2);
      vec.add(8);
      System.out.println("The Vector elements are: " + vec);
      vec.remove(2);
      System.out.println("The Vector elements are: " + vec);
   }
}

The output of the above program is as follows:

The Vector elements are: [4, 1, 6, 2, 8]
The Vector elements are: [4, 1, 2, 8]

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. After that, Vector.remove() method is used to remove the element at index 2 in the Vector. Then the Vector is displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(6);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
vec.remove(2);
System.out.println("The Vector elements are: " + vec);

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements