Java Collections.nCopies()

Java Collections.nCopies()

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

语法:

public static < **T** > List< **T** > nCopies(int number, **T** object)

其中,number是对象的副本数量
的数量,而object表示
元素,它将在返回的列表中出现number
在返回的列表中。T代表通用类型。

异常: 如果数字的值小于0,该函数会抛出 IllegalArgumentException

例如:

// 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  

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程