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 { try { // 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); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } } }
输出: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 { try { // 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); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } } }
输出:List elements before fill: [20, 30, 40] List elements after fill: [500, 500, 500]
相关用法
- Java Collections max()用法及代码示例
- Java Collections min()用法及代码示例
- Java Collections singletonMap()用法及代码示例
- Java Collections synchronizedMap()用法及代码示例
- Java Collections synchronizedList()用法及代码示例
- Java Collections checkedSortedMap()用法及代码示例
- Java Collections checkedSet()用法及代码示例
- Java Collections synchronizedSortedSet()用法及代码示例
- Java Collections synchronizedSortedMap()用法及代码示例
- Java Collections synchronizedSet()用法及代码示例
- Java Collections checkedSortedSet()用法及代码示例
- Java Collections indexOfSubList()用法及代码示例
- Java Collections list()用法及代码示例
- Java Collections replaceAll()用法及代码示例
- Java Collections singletonList()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections fill() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。