📜  Java中的集合 fill() 方法和示例

📅  最后修改于: 2022-05-13 01:54:49.357000             🧑  作者: Mango

Java中的集合 fill() 方法和示例

Java.util.Collections类的fill()方法用于将指定列表的所有元素替换为指定元素。

此方法以线性时间运行。

句法:

public static  void fill(List list, T obj)

参数:此方法将以下参数作为参数

  • list --要填充指定元素的列表。
  • obj –用于填充指定列表的元素。

以下是说明fill()方法的示例

示例 1:

// Java program to demonstrate
// fill() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        // creating object of List
        List arrlist = new ArrayList();
  
        // Adding element to srclst
        arrlist.add("A");
        arrlist.add("B");
        arrlist.add("C");
  
        // print the elements
        System.out.println("List elements before fill: "
                           + arrlist);
  
        // fill the list
        Collections.fill(arrlist, "TAJMAHAL");
  
        // print the elements
        System.out.println("\nList elements after fill: "
                           + arrlist);
    }
}
输出:
List elements before fill: [A, B, C]

List elements after fill: [TAJMAHAL, TAJMAHAL, TAJMAHAL]

示例 2:

// Java program to demonstrate
// fill() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
  
        // creating object of List
        List arrlist = new ArrayList();
  
        // Adding element to srclst
        arrlist.add(20);
        arrlist.add(30);
        arrlist.add(40);
  
        // print the elements
        System.out.println("List elements before fill: "
                           + arrlist);
  
        // fill the list
        Collections.fill(arrlist, 500);
  
        // print the elements
        System.out.println("\nList elements after fill: "
                           + arrlist);
    }
}
输出:
List elements before fill: [20, 30, 40]

List elements after fill: [500, 500, 500]