Open In App

Replacing All Elements of Java Vector

All the elements of a vector can be replaced by a specific element using java. util. Collections. fill() method.The fill() method of java.util.Collections class is used to replace all of the elements of the specified list with the specified element.

VECTOR BEFORE REPLACING

VECTOR AFTER REPLACING

Algorithm :



This method runs in linear time.

Syntax:



public static  void fill(List list, T obj)

Parameters: This method takes following argument as parameter

Code:




// Java program for Replacing All 
// Elements of Java Vector
  
import java.io.*;
import java.util.Vector;
import java.util.Collections;
class GFG {
    public static void main (String[] args)
    {
      // Create a vector
      Vector<Integer> storage =new Vector<Integer>(6);
        
      // adding elements to the vector
      storage.add(20);      
      storage.add(10);
      storage.add(30);
      storage.add(40);
      storage.add(60);
      storage.add(70);
        
      // val to replace with 
      int val=1;
        
        
      // printing the vector before replacing 
      System.out.println("Vector before Replacing is: " + storage);
        
      // using Collections.fill to replace all the elements
      Collections.fill(storage,val);
        
        
      //printing the vector after replacing 
      System.out.println("Vector after Replacing is:  " + storage);
       
        
        
    }
}

Output
Vector before Replacing is: [20, 10, 30, 40, 60, 70]
Vector after Replacing is:  [1, 1, 1, 1, 1, 1]

Article Tags :