java.util.Collections.ncopies() Method


Advertisements


Description

The ncopies(int, T) method is used to returns an immutable list consisting of n copies of the specified object.

Declaration

Following is the declaration for java.util.Collections.ncopies() method.

public static <T> List<T> nCopies(int n, T o)

Parameters

  • n -- The number of elements in the returned list.

  • o -- The element to appear repeatedly in the returned list.

Return Value

The method call returns an immutable list consisting of n copies of the specified object.

Exception

  • IllegalArgumentException -- This is thrown if n < 0.

Example

The following example shows the usage of java.util.Collections.ncopies()

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
   // create a list with n copies 
   List list = Collections.nCopies(5, "tuitorial Point");
      
   // create an iterator
   Iterator itr = list.iterator();
      
   System.out.println("Values are :");
   while (itr.hasNext()){
   System.out.println(itr.next());
   }
   }      
}

Let us compile and run the above program, this will produce the following result.

Values are :
tuitorial Point
tuitorial Point
tuitorial Point
tuitorial Point
tuitorial Point

java_util_collections.htm

Advertisements