Home »
Java programming language
Java Collections fill() Method with Example
Collections Class fill() method: Here, we are going to learn about the fill() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 03, 2020
Collections Class fill() method
- fill() method is available in java.util package.
- fill() method is used to fill all the elements in the given list(l) with the given element (ele).
- fill() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then also we will not get an error.
- fill() method may throw an exception at the filling the list with the given element.
UnsupportedOperationException: This exception may throw when the given parameter List(l) un-support set operation.
Syntax:
public static void fill(List l, Type ele);
Parameter(s):
- List l – represents the list object to be filled with given element(ele).
- Type ele – represents the element(ele) with which to replace the elements in the list.
Return value:
The return type of this method is void, it returns nothing.
Example:
// Java program is to demonstrate the example
// of void fill() of Collections
import java.util.*;
public class Fill {
public static void main(String args[]) {
// Instantiate a LinkedList
List link_l = new LinkedList();
// By using add() method is to
// add elements in linked list
link_l.add(10);
link_l.add(20);
link_l.add(30);
link_l.add(40);
link_l.add(50);
// Display LinkedList
System.out.println("link_l: " + link_l);
// By using fill() method is to
// fill the linked list with the
// given element "100"
Collections.fill(link_l, 100);
//Display LinkedList
System.out.println("Collections.fill(link_l,100): " + link_l);
}
}
Output
link_l: [10, 20, 30, 40, 50]
Collections.fill(link_l,100): [100, 100, 100, 100, 100]