java.util.Collections.fill() Method


Advertisements


Description

The fill(List<? super T>, T) method is used to replace all of the elements of the specified list with the specified element.

Declaration

Following is the declaration for java.util.Collections.fill() method.

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

Parameters

  • list − This is the list to be filled with the specified element.

  • obj − This is the element with which to fill the specified list.

Return Value

NA

Exception

UnsupportedOperationException − This is thrown if the specified list or its list-iterator does not support the set operation.

Example

The following example shows the usage of java.util.Collections.fill()

Live Demo
package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String args[]) {

      // create array list object       
      List arrlist = new ArrayList();

      // populate the list
      arrlist.add("A");
      arrlist.add("B");
      arrlist.add("C");

      System.out.println("List elements before fill: "+arrlist);

      // fill the list with 'TP'
      Collections.fill(arrlist,"TP");

      System.out.println("List elements after fill: "+arrlist);    
   }
}

Let us compile and run the above program, this will produce the following result.

List elements before fill: [A, B, C]
List elements after fill: [TP, TP, TP]

java_util_collections.htm

Advertisements