Last Updated : 06 Dec, 2024
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
// 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);
}
}
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.
Appends the specified element to the end of this Vector.
Syntax:boolean add(Object element)
Below program illustrates the working of java.util.Vector.add(Object element) method:
Example:
Java
// 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);
}
}
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.
Example:
Java
// 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);
}
}
Vector Initial : [1, 3, 5] Vector After Addition : [1, 2, 3, 4, 5]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4