Java – Creating ArrayList using Collections.nCopies method

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

1. Creating ArrayList using nCopies method :

Method signature:

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

Where,

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

CreateArrayListUsingNCopies.java

package in.bench.resources.java.collections;

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) {
		super();
		this.custId = custId;
		this.custName = custName;
	}

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

Output:

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]]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Iterate through ArrayList in 5 ways
Java - Conversion of Arrays to List