Java Collections.fill() Method

 


In Java, the fill() method of the java.util.Collections class is used to replace all of the elements of a specified list with a given element. This method is useful when you want to initialize a list with a default value or reset all the elements to a particular value.

Syntax

The syntax of the fill() method is:

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

Here, the T is a type parameter that represents the type of the elements in the list. The obj parameter is the value with which the list is to be filled. The list parameter is the list to be filled with the specified element.

Parameters

The fill() method takes two parameters:

  • list: The list to be filled with the specified element.
  • obj: The element with which to fill the specified list.

Return Value

The fill() method does not return anything. It modifies the original list by replacing all the elements with the specified element.

Example

Here's an example that demonstrates how to use the fill() method to replace all the elements of a list with a given value:

java
import java.util.*; public class Example { public static void main(String[] args) { // Create a list of integers List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5)); // Fill the list with the value 0 Collections.fill(list, 0); // Print the modified list System.out.println(list); // Output: [0, 0, 0, 0, 0] } }

In this example, we first create a list of integers using the Arrays.asList() method. Then, we use the fill() method of the Collections class to replace all the elements of the list with the value 0. Finally, we print the modified list using the System.out.println() method.

Conclusion

The fill() method of the java.util.Collections class is a simple and useful method that can save you a lot of time when you want to initialize a list with a default value or reset all the elements to a particular value. By using this method, you can easily modify the contents of a list without having to write a loop to traverse the list and replace each element individually.

Previous Post Next Post