Wednesday, July 3, 2024
HomeLanguagesJavaCreate List containing n Copies of Specified Object in Java

Create List containing n Copies of Specified Object in Java

To create a Java List containing n Copies of a specified Object, nCopies() method of java.util.Collections class can be used. The nCopies() method takes two parameters – n the length of the list and the object which has to be copied n times in the list.

Example:

Input : n = 4, Object = "Hello"
Output: listOfObjects = ["Hello", "Hello", "Hello", "Hello"]

Input : n = 3, Object = 3
Output: listOfObjects = [3, 3, 3]

Declaration:

public static nCopies(int length, Object object)

Return Value: An immutable List containing n copies of the specified object.

Exception Throws: IllegalArgumentException
if the length provided is less than 0
i.e, n < 0

Java




// Create List containing n Copies
// of Specified Object in java
import java.io.*;
import java.util.Collections;
import java.util.List;
  
class GFG {
    public static void main(String[] args)
    {
        int n = 5;
        Object myObj = "GFG";
  
        List myList = Collections.nCopies(n, myObj);
  
        System.out.println(myList);
    }
}


Output

[GFG, GFG, GFG, GFG, GFG]
Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments