The fill() method of java.util.Collections class is used to replace all of the elements of the specified list with the specified element.
This method runs in linear time.
Syntax:
public static void fill(List list, T obj)
Parameters: This method takes following argument as parameter
- list – the list to be filled with the specified element.
- obj – The element with which to fill the specified list.
Below are the examples to illustrate the fill() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
List<String> arrlist = new ArrayList<String>();
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
System.out.println("List elements before fill: "
+ arrlist);
Collections.fill(arrlist, "TAJMAHAL");
System.out.println("\nList elements after fill: "
+ arrlist);
}
}
|
Output:
List elements before fill: [A, B, C]
List elements after fill: [TAJMAHAL, TAJMAHAL, TAJMAHAL]
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
List<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(20);
arrlist.add(30);
arrlist.add(40);
System.out.println("List elements before fill: "
+ arrlist);
Collections.fill(arrlist, 500);
System.out.println("\nList elements after fill: "
+ arrlist);
}
}
|
Output:
List elements before fill: [20, 30, 40]
List elements after fill: [500, 500, 500]
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
07 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...