Collections.nCopies()的作用是返回一個不可變的列表,其中包含給定對象的n個副本。如果我們要創建具有給定對象的n個副本的列表,則此函數很有幫助。新分配的數據對象很小,即它包含對數據對象的單個引用。
用法:
public static <T> List<T> nCopies(int number, T object) where, number is the number of copies of object and object represents the element which will appear number times in the returned list. T represents generic type.
異常:如果number的值小於0,則該函數引發IllegalArgumentException。
例:
Java
// Java code to show implementation
// of Collections.nCopies()
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a list where first argument
// represents the number of copies and
// the second argument represents the
// element to be copied for 'number' times
// This will create 4 copies of the objects.
List list = Collections.nCopies(4, "GeeksforGeeks");
// Displaying the list returned
System.out.println("The list returned is :");
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println("\n");
List list1 = Collections.nCopies(3, "GeeksQuiz");
// Displaying the list returned
System.out.println("The list returned is :");
Iterator itr1 = list1.iterator();
while (itr1.hasNext()) {
System.out.print(itr1.next() + " ");
}
System.out.print("\n");
}
}
輸出:
The list returned is : GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks The list returned is : GeeksQuiz GeeksQuiz GeeksQuiz
相關用法
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java.util.concurrent.Phaser用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java.util.concurrent.RecursiveTask用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java.util.function.IntPredicate用法及代碼示例
- Java Java.util.concurrent.RecursiveAction用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Collections.nCopies() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。