What is the vector.add method in Java?

The add() method of the Vector class can be used to add an element at the end of the vector object.


Vector is a growable array of objects. Elements are mapped to an index.


Syntax


public boolean add(E element);

Return value

This method returns true if the Vector changes as a result of the call. Otherwise, it returns false.

Code

import java.util.Vector;
class VectorAddExample {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.add(1);
vector.add(2);
vector.add(3);
vector.add(4);
// Print vector
System.out.println("The Vector is: " + vector);
// Adding new elements to the end
vector.add(5);
// Printing the new vector
System.out.println("The Vector is: " + vector);
}
}

Explanation

In the code above:

  • We create a Vector with the name vector.

  • We add elements, 1,2,3,4, to the vector with the add method. The elements are added to the end of the vector object.

  • We use the add method again to add 5 as the last element of the vector.

Free Resources