Skip to content
Related Articles
Open in App
Not now

Related Articles

Replacing All Elements of Java Vector

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 28 Dec, 2020
Improve Article
Save Article

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.

  • Let’s consider the following vector:


  • Let’s say that we have to replace all the elements by Value 1, then after replacing each value in the given vector by 1 are vector should become like the figure below :-


Algorithm :

  • A naive way of doing this is to traverse the entire vector and replace each element with the given value. However, in Java, we have a Built-in method Collections.fill() method as a part of Java Collections which replaces all the elements.

This method runs in linear time.


public static  void fill(List list, T obj)

Parameters: This method takes following argument as parameter

  • list – the list to be filled with the specified element.
  • obj – The element with which to fill the specified list.



// Java program for Replacing All 
// Elements of Java Vector
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
      // 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
      //printing the vector after replacing 
      System.out.println("Vector after Replacing is:  " + storage);


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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!