Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collections.fill in Java?

abhilash

The fill function in the Collections class is used to replace all the elements of a list with a given element. Collections is defined in the util package in Java, so you must import the util package before you can use the fill function.

import java.util.Collections;

Syntax

The syntax for the fill function is shown below:

Collections.fill(list, element)

Method signature

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

Parameters

  • List<? super T> list: the list to be filled.
  • T obj: the element that is used to fill the list.

<T> is the class of the objects in the passed list.

To learn more about parameter types, click here.

Return value

The method doesn’t return anything. Instead, the list is modified.

Code

The example below will help you understand the fill function better. We first define the list and populate the list with certain elements. Then, we use the fill function to replace all the values of the list with the passed element.

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

public class Main {

    public static void main(String[] args){
        List<String> stringList = new ArrayList<>();
        stringList.add("educative");
        stringList.add("java");
        stringList.add("python");
        stringList.add("C#");
        System.out.println("List Before - " + stringList);
        String element = "hello";
        Collections.fill(stringList, element);
        System.out.println("List After - " + stringList);

    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring