Create an ArrayList of n Copies using Collections

Problem Statement:

How to Create an ArrayList of n Copies using Collections?

 Create an ArrayList of n Copies using Collections

Description:

  • Collections.nCopies – Returns an immutable list consisting of specified number of copies of the specified “TECHNOSTIXS” object.
  • The newly allocated data object is tiny (it contains a single reference to the data object).
  • This method is useful in combination with the List.addAll method to grow lists.
  • The returned list “nameList” is serializable.
  • Throws illegalArgumentException if n is less than 0.

Create an ArrayList of n Copies using Collections

Sample Code to Create an ArrayList of n Copies using Collections

package com.stixs.java.collections;

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

/**
 * The Class STXCreateArrayListOfNCopies.Returns an immutable list consisting of
 * specified number of copies of the specified "TECHNOSTIXS" object.
 */
public class STXCreateArrayListOfNCopies {

  public static void main(String[] args) {

  /*
  * Collections.nCopies - Returns an immutable list consisting of
  * specified number of copies of the specified "TECHNOSTIXS" object.
  * 
  * The newly allocated data object is tiny (it contains a single
  * reference to the data object).
  * 
  * This method is useful in combination with the List.addAll method to
  * grow lists. 
  * 
  * The returned list "nameList" is serializable.
  * 
  * Throws illegalArgumentException if n is less than 0
  */

  List<String> nameList = Collections.nCopies(4, "TECHNOSTIXS");

  // iterate through newly created list
  System.out.println("STXCreateArrayListOfNCopies ArrayList contains, ");

  Iterator<String> nameIterator = nameList.iterator();
  while (nameIterator.hasNext()) {
   System.out.println(nameIterator.next());
  }
 }
}
seperator

Output:

STXCreateArrayListOfNCopies ArrayList contains, 
TECHNOSTIXS
TECHNOSTIXS
TECHNOSTIXS
TECHNOSTIXS

seperator

Java API Classes and Methods used to Create an ArrayList of n Copies using Collections

Collections.cCopies

IMG SRC: From Oracle Java Docs

seperator

Reference

Refer below path to get the complete details about Java Collections class.

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html

seperator

You may also like this

seperator

About TechnoStixs.com

Create an ArrayList of n Copies using Collections

TechnoStixs.com is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.

1,321 total views, 3 views today

Add comment