Java Filling List elements with fill()


With the Collections fill() static method (Collections methods are known as algorithms), a data structure can be filled up (or replaced) with one element. After this method call, the data structure will have the same element.

Following is the method signature

  • static void fill(List list1, Object obj1): Replaces all the elements of list1 with obj1. Earlier elements are lost. This method is used to fill all the elements with the same values.

Following program uses the above method.

import java.util.*;
public class CollectionsFill
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(50);
    myList.add(10);
    myList.add(20);
    myList.add(40);
    System.out.println("Elements before fill: " + myList);

    Collections.fill(myList, 0);
    System.out.println("Elements after fill: " + myList); 

    ArrayList namesList = new ArrayList();
    namesList.add("hello");
    namesList.add("world");
    namesList.add(20);
    System.out.println("\nElements before fill: " + namesList);

    Collections.fill(namesList, null);
    System.out.println("Elements after fill: " + namesList); 
  }
}

Java Filling List elements with fill()
Output screenshot of Java Filling List elements with fill()

ArrayList myList = new ArrayList();
myList.add(50);

An ArrayList object myList is created and added four integer elements with add() method inherited from List interface.

Collections.fill(myList, 0);

All the four elements are replaced with 0 value.

ArrayList namesList = new ArrayList();
namesList.add(“hello”);

Another ArrayList object namesList is created and added with three string elements.

Collections.fill(namesList, null);

All the three string elements are replaced with null values using fill() method. This method is very useful to fill all the elements with the same value (or one value only).

Leave a Comment

Your email address will not be published.