Replace an element at a specified index of the Vector in Java


An element in a Vector can be replaced at a specified index using the java.util.Vector.set() method. This method has two parameters i.e the index at which the Vector element is to be replaced and the element that it should be replaced with. Vector.set() method returns the element that was at the position specified at the index previously.

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(7);
      vec.add(3);
      vec.add(9);
      vec.add(1);
      vec.add(5);
      System.out.println("The Vector elements are: " + vec);
      vec.set(1, 6);
      System.out.println("The Vector elements are: " + vec);
   }
}

The output of the above program is as follows:

The Vector elements are: [7, 3, 9, 1, 5]
The Vector elements are: [7, 6, 9, 1, 5]

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. Then Vector.set() is used to replace the element 3 with element 6 at index 1. Then the Vector is displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector(5);
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(1);
vec.add(5);
System.out.println("The Vector elements are: " + vec);
vec.set(1, 6);
System.out.println("The Vector elements are: " + vec);

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements