Replace All Elements Of ArrayList with with Java Collections


In order to replace all elements of ArrayList with Java Collections, we use the Collections.fill() method. The static void fill(List list, Object element) method replaces all elements in the list with the specified element in the argument.

Declaration −The java.util.Collections.fill() method is declared as follows −

public static <T> void fill(List<? super T> list, T obj)

where obj acts as a filler element to the List list.

Let us see a program to replace all elements of ArrayList with Java collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(7);
      Collections.fill(list,98);
      System.out.println(list);
   }
}

Output

[98, 98, 98]

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements