Add Elements to a Vector in Java



A dynamic array is implemented by a Vector. This means an array that can grow or reduce in size as required.

Elements can be added at the end of the 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);
      vec.add(4);
      vec.add(1);
      vec.add(7);
      vec.add(3);
      vec.add(5);
      vec.add(9);
      vec.add(2);
      vec.add(8);
      vec.add(6);
      System.out.println("The Vector elements are: " + vec);
   }
}

The output of the above program is as follows −

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

Now let us understand the above program.

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

Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(3);
vec.add(5);
vec.add(9);
vec.add(2);
vec.add(8);
vec.add(6);
System.out.println("The Vector elements are: " + vec);
Updated on: 2020-06-30T08:11:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements