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.
Syntax:
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.
Code:
Java
// 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]