Vector add() Method in Java
Last Updated :
06 Dec, 2024
Improve
To add an element to a Vector in Java, you can use the add() method, which appends an element to the end of the vector.
Implementation:
// Java code to illustrate Adding
// Element in Vector
import java.util.*;
public class GFG
{
public static void main(String args[])
{
// Creating an empty Vector
Vector<String> v = new Vector<String>();
// Use add() method to add elements in the vector
v.add("A");
v.add("B");
v.add("C");
v.add("D");
v.add("F");
// Printing the new vector
System.out.println("The new Vector is: " + v);
}
}
Output
The new Vector is: [A, B, C, D, F]
Now there are two versions of Vector add() method i.e one with the specified index and one without any index.
1. void add(Object element)
Appends the specified element to the end of this Vector.
Syntax:
boolean add(Object element)
- Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the vector.
- Return Value: This method returns True after successful execution, else False.
Below program illustrates the working of java.util.Vector.add(Object element) method:
Example:
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class GFG
{
public static void main(String args[])
{
// Creating an empty Vector
Vector<String> v = new Vector<String>();
// Use add() method to add elements in the vector
v.add("A");
v.add("B");
v.add("C");
Boolean t = v.add("D");
// checking if successful
if(t==true)
System.out.println("Sucessful");
else
System.out.println("Failed");
// Printing the new vector
System.out.println("The new Vector is: " + v);
}
}
Output
Sucessful The new Vector is: [A, B, C, D]
2. void add(int index, Object element)
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).
Syntax:
void add(int index, Object element)
Parameters: This method accepts two parameters as described below.
- index: The index at which the specified element is to be inserted.
- element: The element which is needed to be inserted.
Example:
// Java Program to demonstrate
// Addition of element at index
import java.util.*;
class GFG
{
public static void main (String[] args)
{
// Creating an empty Vector
Vector<Integer> v = new Vector<Integer>();
// Use add() method to add elements in the vector
v.add(1);
v.add(3);
v.add(5);
// Present Vector
System.out.println("Vector Initial : " + v);
// Adding new element at index
int index= 1;
v.add(index,2);
// Adding new element at index
index = 3;
v.add(index,4);
// Final Vector
System.out.println("Vector After Addition : " + v);
}
}
Output
Vector Initial : [1, 3, 5] Vector After Addition : [1, 2, 3, 4, 5]