Open In App

How to Replace an Element at a Specific Index of the Vector in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here.

Examples 

Input  : Vector= ["Harry","Steve","Vince","David","Matt"],Index=1,Element ="Mark"
Output : Vector= ["Harry","Mark","Vince","David","Matt"]
 
Input  : Vector= ["Harry","Steve","Vince","David","Matt"],Index=2,Element ="Jack"
Output : Vector= ["Harry","Mark","Jack","David","Matt"]

Approach:

An element in the vector can be replaced at a particular/specified index with another element using set() method, or we can say java.util.Vector.set() method.

Syntax:

Vector.set(int index, Object element)

Parameters: This function accepts two mandatory parameters as shown in the above syntax and described below.

  • index: This is of integer type and refers to the position of the element that is to be replaced from the vector.
  • element: It is the new element by which the existing element will be replaced and is of the same object type as the vector.

Return Value: The method returns the previous value from the vector that is replaced with the new value.

Java




// Java Program to replace a element at a particular index
// in vector
  
import java.util.Vector;
public class GFG {
    public static void main(String[] args)
    {
        // making a new vector object
        Vector<String> vector = new Vector<String>();
        
        // adding elements to the vector.
        vector.add("Harry");
        vector.add("Steve");
        vector.add("Vince");
        vector.add("David");
        vector.add("Matt");
  
        System.out.println("Vector elements before replacement: ");
        
        for (int i = 0; i < vector.size(); i++) 
        {
            System.out.print(vector.get(i) + " ");
        }
        
        System.out.println();
  
        // Replacing index 1 element
        vector.set(1, "Mark");
        // Replacing index 2 element
        vector.set(2, "Jack");
  
        System.out.println("Vector elements after replacement: ");
        
        for (int i = 0; i < vector.size(); i++) 
        {
            System.out.print(vector.get(i) + " ");
        }
        
        System.out.println();
    }
}


Output

Vector elements before replacement: 
Harry Steve Vince David Matt 
Vector elements after replacement: 
Harry Mark Jack David Matt 


Last Updated : 19 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads