Java Collections fill()方法及实例

Java Collections 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<Integer>
        List<String> arrlist = new ArrayList<String>();
  
        // 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<Integer>
        List<Integer> arrlist = new ArrayList<Integer>();
  
        // 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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程