📜  Java中的 Collections.nCopies()

📅  最后修改于: 2022-05-13 01:54:54.937000             🧑  作者: Mango

Java中的 Collections.nCopies()

Collections.nCopies()的作用是返回一个不可变列表,其中包含给定对象的 n 个副本。如果我们想创建一个包含 n 个给定对象副本的列表,这个函数会很有帮助。新分配的数据对象很小,即它包含对数据对象的单个引用。

句法 :

public static  List 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