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.
Vectoris 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 VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(1);vector.add(2);vector.add(3);vector.add(4);// Print vectorSystem.out.println("The Vector is: " + vector);// Adding new elements to the endvector.add(5);// Printing the new vectorSystem.out.println("The Vector is: " + vector);}}
Explanation
In the code above:
-
We create a
Vectorwith the namevector. -
We add elements,
1,2,3,4, to thevectorwith theaddmethod. The elements are added to the end of thevectorobject. -
We use the
addmethod again to add5as the last element of thevector.