Collections.nCopies() Method in Java with Example

Learn how the Collections.nCopies() method in Java creates a list containing multiple copies of the same object.it is used to return an unmodifiable list containing the specified number of copies of the same object.

This method is defined in the java.util.Collections class.

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

    • n: Specifies the number of copies of the object to be returned in the list.
    • o: Specifies the object to be repeated in the list.
  • Collections.nCopies(4, “welcome”) creates a list containing four copies of the string “welcome”.
  • The returned list is passed to the ArrayList constructor, which creates a mutable ArrayList .
  • The analyze(List<String> data) method checks whether data.size() > 5.
  • If the list size is greater than 5, the method throws a ListTooLargeException.
  • If the list size is 5 or less, the program prints the list.
				
					import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class ListToLargeException extends RuntimeException {

    public ListToLargeException(String message) {
        super(message);
    }
}

public class DemoCopies {

    public void analyze(List<String> data) {
        if (data.size() > 5) {
            throw new ListToLargeException(
                "List cannot contain more than 5 elements"
            );
        }
    }

    public static void main(String[] args) {

        DemoCopies demo = new DemoCopies();

        List<String> listData =
                new ArrayList<>(Collections.nCopies(4, "welcome"));

        demo.analyze(listData);

        System.out.println("nCopies list returned is: " + listData);
    }
}
				
			

Output :-
nCopies list returned is: [welcome, welcome, welcome, welcome]

Important Points About Collections.nCopies()

  • Collections.nCopies() is a static method available in the java.util.Collections class.
  • It returns a list containing the specified number of copies of the given object.
  • The returned list is unmodifiable, so you cannot add or remove elements from it.
				
					List<String> list = Collections.nCopies(4, "welcome");
list.add("Java"); // UnsupportedOperationException
				
			
  • All elements in the list refer to the same supplied object. The method does not create separate clones of the object.
  • The method can be used with different object types:
				
					List<Integer> numbers = Collections.nCopies(5, 10);