Collections.fill() in Java
The fill() method of java.util.Collections class is used to replace all of the elements of the specified list with the specified element.
Function Declaration:
public static<T> void fill(List<? super T> list, T obj)
This is a generic function declaration signified by <T> with the following content:
- obj: The element with which to fill the specified list. It is of T type.
- list: The list to be filled with the specified element. The type of the list is dependent on the type of obj, i.e., T. If an object is of type T, then the list type must be of type T or an ancestor of T. This is understood by the super keyword.
The "?" denotes the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
Example:
// Java program to demonstrate // fill() method // for Integer value
import java.util.*;
public class GFG { public static void main(String[] argv) { // creating an object of List<Integer> List<Integer> al = new ArrayList<Integer>();
scss // Adding elements to the list
al.add(10);
al.add(20);
al.add(30);
// fill the list
Collections.fill(al, 5);
// print the elements
System.out.println(al);
}
}
Output: [5, 5, 5]
In the example, we create an object of List<Integer>, add elements to the list, and then use the fill() method to replace all the elements with the integer value 5. Finally, we print the elements to verify the replacement.