Add elements at the end of a Vector in Java


Elements can be added at the end of a Vector using the java.util.Vector.add() method. This method has a single parameter i.e. the element to be added. It returns true if the element is added to the Vector as required and false otherwise.

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 = 1; i <= 10; i++) {
         vec.add(i);
      }
      System.out.println("The Vector elements are: " + vec);
   }
}

Output

The Vector elements are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector using a for loop. Finally, the Vector elements are displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector(5);
for (int i = 1; i <= 10; i++) {
   vec.add(i);
}
System.out.println("The Vector elements are: " + vec);

Updated on: 30-Jul-2019

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements