收藏。Java中的nCopies()

角色 收藏。士官() 返回一个不可变列表,其中包含给定对象的n个副本。如果我们想创建一个包含给定对象n个副本的列表,这个函数会有所帮助。新分配的数据对象很小,即它包含对该数据对象的单个引用。

null

语法:

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. 

例外情况: 函数抛出 非法数据异常 如果价值 数字 小于0。

例子:

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( "" );
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( "" );
}
}


The list returned is :
GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks 

The list returned is :
GeeksQuiz GeeksQuiz GeeksQuiz  
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享