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 :-
- 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.
Vector before Replacing is: [20, 10, 30, 40, 60, 70] Vector after Replacing is: [1, 1, 1, 1, 1, 1]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.