Java Collections - fill() Method
The java.util.Collections.fill() method is used to replace all of the elements of the specified list with the specified element.
Syntax
public static <T> void fill(List<? super T> list, T obj)
Here, T is the type of element in the list.
Parameters
list |
Specify the list to be filled with the specified element. |
obj |
Specify the element with which to fill the specified list. |
Return Value
void type.
Exception
Throws UnsupportedOperationException, if the specified list or its list-iterator does not support the set operation.
Example:
In the example below, the java.util.Collections.fill() method is used to fill the given list with specified element.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a list object List<Integer> MyList = new ArrayList<Integer>(); //populating MyList MyList.add(10); MyList.add(20); MyList.add(30); //printing the list System.out.println("MyList contains: " + MyList); //fill the list with 25 Collections.fill(MyList, 25); //printing the list System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30] MyList contains: [25, 25, 25]
❮ Java.util - Collections