Home » Java programming language

Java Collections nCopies() Method with Example

Collections Class nCopies() method: Here, we are going to learn about the nCopies() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 08, 2020

Collections Class nCopies() method

  • nCopies() method is available in java.util package.
  • nCopies() method is used to return a List (i.e. List is immutable) that consists of multiple copies (n copies) of the given object (obj).
  • nCopies() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • nCopies() method may throw an exception at the time of containing n copies of the given object.
    IllegalArgumentException: This exception may throw when the given parameter (no_of_ele) is less than 0.

Syntax:

    public static List nCopies(int no_of_ele, Type obj);

Parameter(s):

  • int no_of_ele – represents the number of elements in the returned type List.
  • Type obj – represents the object to appear multiple times in the returned List.

Return value:

The return type of this method is List, it returns an immutable list made up of "n" number of copies of the given object (obj).

Example:

//Java program is to demonstrate the example of
// nCopies(int no_of_ele, Type obj) method of Collections

import java.util.*;

public class NcopiesOfCollections {
    public static void main(String[] args) {
        // Instantiates a list object with
        // 10 copies
        List l = Collections.nCopies(10, "INCLUDEHELP");

        // By using iterator() method is
        // to iterate list object
        Iterator it_r = l.iterator();

        System.out.println("Collections.nCopies(): ");

        while (it_r.hasNext()) {
            System.out.println(it_r.next());
        }
    }
}

Output

Collections.nCopies(): 
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP
INCLUDEHELP



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.