Replace all the elements of a Vector with Collections.fill() in Java

Java 8Object Oriented ProgrammingProgramming

All the elements of a vector can be replaced by a specific element using java.util.Collections.fill() method. This method requires two parameters i.e. the Vector and the element that replaces all the elements in the Vector. No value is returned by the Collections.fill() method.

A program that demonstrates this is given as follows:

Example

 Live Demo

import java.util.Collections;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector(5);
      vec.add(7);
      vec.add(4);
      vec.add(1);
      vec.add(2);
      vec.add(9);
      System.out.println("The Vector elements are: " + vec);
      Collections.fill(vec, 3);
      System.out.println("The Vector elements are: " + vec);
   }
}

The output of the above program is as follows:

The Vector elements are: [7, 4, 1, 2, 9]
The Vector elements are: [3, 3, 3, 3, 3]

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. Collections.fill() method is used to replace all the elements of the Vector with element 3.

Then the Vector is displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector(5);
vec.add(7);
vec.add(4);
vec.add(1);
vec.add(2);
vec.add(9);
System.out.println("The Vector elements are: " + vec);
Collections.fill(vec, 3);
System.out.println("The Vector elements are: " + vec);
raja
Published on 07-Feb-2019 16:10:19
Advertisements