Home » Java Collections nCopies() Method with Examples

Java Collections nCopies() Method with Examples

by Online Tutorials Library

Java Collections nCopies() Method

The nCopies() method of Java Collections class is used to get an immutable list consisting of n copies of the specified object.

Syntax

Following is the declaration of nCopies() method:

Parameter

Parameter Description Required/Optional
n It is the number of elements in the returned list. Required
o It is the element to appear repetedly in the returned list. Required

Returns

The nCopies() method returns an immutable list consisting of n copies of the specified object.

Exceptions

IllegalArgumentException– It throws this exception if the number of elements is less then zero i.e. n < 0.

Compatibility Version

Java 1.4 and above

Example 1

Test it Now

Output:

Output: [TutorAspire, TutorAspire , TutorAspire ]  

Example 2

Test it Now

Output:

Output of Atomic Integer are:  [0, 0, 0]  [1, 1, 1]  

Example 3

Test it Now

Output:

List elements:   SSSIT.COM  SSSIT.COM  SSSIT.COM  SSSIT.COM  SSSIT.COM  

You may also like