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.
- Let’s consider the following vector:
VECTOR BEFORE REPLACING
- 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 :-
VECTOR AFTER REPLACING
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
import java.io.*;
import java.util.Vector;
import java.util.Collections;
class GFG {
public static void main (String[] args)
{
Vector<Integer> storage = new Vector<Integer>( 6 );
storage.add( 20 );
storage.add( 10 );
storage.add( 30 );
storage.add( 40 );
storage.add( 60 );
storage.add( 70 );
int val= 1 ;
System.out.println( "Vector before Replacing is: " + storage);
Collections.fill(storage,val);
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]
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...