Creating ArrayList using nCopies method of Collections class

In this article, we will discuss how to create ArrayList using Collections class’s utility nCopies() method

This is used to create ArrayList containing multiple copies of same elements or say same objects


Creating ArrayList using nCopies method :

Method signature:

public static List nCopies(int n, Object object);


  • n – number of copies to be created
  • object – element value (or object for which multiple copies required)


import java.util.ArrayList;
import java.util.Collections;

public class CreateArrayListUsingNCopies {

	public static void main(String[] args) {

		// 7 copies of String object
		ArrayList<String> lstString = new ArrayList<String>(
				Collections.nCopies(7, "BRN"));

		// printing List of String object
		System.out.println("ArrayList of String objects : "
				+ lstString);

		// create a customer object
		Customer cust = new Customer(101, "Berry");

		// 3 copies of Customer object - user-defined object
		ArrayList<Customer> lstCustomer = new ArrayList<Customer>(
				Collections.nCopies(3, cust));

		// printing List of Customer object
		System.out.println("\n\nArrayList of Customer objects : "
				+ lstCustomer);

class Customer {

	// member variables
	int custId;
	String custName;

	// 2-arg constructors
	public Customer(int custId, String custName) {
		this.custId = custId;
		this.custName = custName;

	// overriding toString method
	public String toString() {
		return "\nCustomer ["
				+ "Id=" + custId 
				+ ", Name=" + custName 
				+ "]";


ArrayList of String objects : [BRN, BRN, BRN, BRN, BRN, BRN, BRN]

ArrayList of Customer objects : [
Customer [Id=101, Name=Berry], 
Customer [Id=101, Name=Berry], 
Customer [Id=101, Name=Berry]]




Happy Coding !!
Happy Learning !!

Various ways to iterate through ArrayList - 5 ways
Conversion of Arrays to List