Java Collections fill()

fill() 用于将指定列表中的所有元素替换为指定元素。

1 语法

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

2 参数

list:指定元素填充的列表。

obj:填充指定列表的元素。

3 返回值

4 Collections fill()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.fill的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create a list object
        List<String> arrlist = new ArrayList<String>();
        //Add elements in the list
        arrlist.add("AAA");
        arrlist.add("BBB");
        arrlist.add("CCC");
        System.out.println("List elements before Replacements: "+arrlist);
        //Fill the list with 'Yiidian'
        Collections.fill(arrlist,"Yiidian");
        System.out.println("List elements after Replacements: "+arrlist);
    }
}

输出结果为:

List elements before Replacements: [AAA, BBB, CCC]
List elements after Replacements: [Yiidian, Yiidian, Yiidian]

5 Collections fill()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.fill的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create a list object
        List<Integer> arrList = Arrays.asList(1,2,3,4);
        //Fill the list with 551
        Collections.fill(arrList,551);
        //Print the List
        for(Integer i :arrList) {
            System.out.print(i +" ");
        }
    }
}

输出结果为:

551 551 551 551 

6 Collections fill()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.fill的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 6; i++)
            list.add("Hi");
        System.out.println("Before Fill: "+list);
        Collections.fill(list, "Hello");
        System.out.println("After Fill: "+list);
    }
}

输出结果为:

Before Fill: [Hi, Hi, Hi, Hi, Hi, Hi]
After Fill: [Hello, Hello, Hello, Hello, Hello, Hello]

 

热门文章

优秀文章