In this source code example, we will demonstrate the usage of the Vector add() method in Java with an example.
Vector add(Object element) Method
boolean add(Object element): This method appends the specified element to the end of this vector.
Vector add(Object element) Method Example
Below program illustrates the working of java.util.Vector.add(Object element) method:
import java.util.Vector;
/*
* Example of add(E e) method
*/
public class VectorExample
{
public static void main( String[] args )
{
// Creating an empty Vector
Vector vector = new Vector<>();
/*
* Appends the specified element to the end of this Vector.
*/
vector.add(100);
vector.add(200);
vector.add(300);
vector.add(400);
vector.add(500);
System.out.println("vector : " + vector);
}
}
Output:
vector : [100, 200, 300, 400, 500]
Vector void add(int index, Object element) Method
This method inserts an element at a specified index in the vector. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one).
Vector void add(int index, Object element) Method Example
Below program illustrates the working of java.util.Vector.add(Object element) method:
// Java code to illustrate boolean add(Object element)
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector programLangs = new Vector();
// Use add() method to add elements in the vector
programLangs.add("C");
programLangs.add("C++");
programLangs.add("Java");
programLangs.add("Python");
programLangs.add("Go");
// Output the present vector
System.out.println("The vector is: " + programLangs);
// Adding new elements to the end
programLangs.add(2, "Scala");
programLangs.add(4, "JavaScript");
// Printing the new vector
System.out.println("The new Vector is: " + programLangs);
}
}
Output:
The vector is: [C, C++, Java, Python, Go] The new Vector is: [C, C++, Scala, Java, JavaScript, Python, Go]