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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。