How to Copy Some Copies of an Object into a List Collection in Java


Here we will use nCopies method of Collections class to create a list consisting n copies of specified copies.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.List;

public class CreateListContainingCopiesSpecifiedObject {

	public static void main(String[] args) {

		// Ready to object
		String element = "A";

		// The nCopies() method has two arguments: the first argument is the
		// number of copies, and the second argument is the object to copy
		List copyList = Collections.nCopies(6, element);

		System.out.println(copyList);

	}

}

Output:

[A, A, A, A, A, A]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments