What is the Vector.addElement method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

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

Syntax

public void addElement(obj)

Parameters

The element to be added to the Vector object is passed as an argument obj.

Return value

This method doesn’t return any value.

Code

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

Explanation

In the code above:

  • We created a new object for the Vector class with the name vector.

  • Then, we added the elements 1,2,3,4 to the vector object using the addElement method. The elements are added to the end of the vector object.

  • We again used the addElement method to add the element 5 to the end of the vector.

Free Resources