Add elements at the middle of a Vector in Java

Java 8Object Oriented ProgrammingProgramming

Elements can be added in the middle of a Vector by using the java.util.Vector.insertElementAt() method. This method has two parameters i.e. the element that is to be inserted in the Vector and the index at which it is to be inserted. If there is an element already present at the index specified by Vector.insertElementAt() then that element and all subsequent elements shift to the right by one.

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);
      for (int i = 0; i < 5; i++) {
         vec.insertElementAt(i + 1, i);
      }
      System.out.println("The Vector elements are: " + vec);
      vec.insertElementAt(9, 1);
      System.out.println("The Vector elements are: " + vec);
   }
}

The output of the above program is as follows −

The Vector elements are: [1, 2, 3, 4, 5]
The Vector elements are: [1, 9, 2, 3, 4, 5]

Now let us understand the above program.

The Vector is created. Then Vector.insertElementAt() is used to add the elements to the Vector at the specified index. Finally, the Vector elements are displayed. A code snippet which demonstrates this is as follows −

Vector vec = new Vector(5);
for (int i = 0; i < 5; i++) {
   vec.insertElementAt(i+1, i);
}
System.out.println("The Vector elements are: " + vec);
vec.insertElementAt(9, 1);
System.out.println("The Vector elements are: " + vec);
raja
Published on 07-Feb-2019 10:56:59
Advertisements