List Fill demo

In this post under Java Collections, I will explain with example the purpose of “fill” static method in “Collections” utility class.

This method takes any list as input and replace all the elements of the list with user given object.

So if we have a list named “entries” containing below elements

[1, 2, 3, 4, 5]

The below method call

Collections.fill(entries, 6);

The output will be

Output

[6, 6, 6, 6, 6]

Below is the complete main class for your reference

Main class

package core.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListFillDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(0);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        System.out.println("Before call to fill: " + list.toString());
        Collections.fill(list, 6);
        System.out.println("After call to fill: " + list.toString());
    }
}

Leave a comment