Powered by Blogger.

Create a List containing n Copies of Specified Object

>> Sunday, October 17, 2010

Create a List containing n Copies of Specified Object This java example shows how to create a list consisting n copies of specified copies using nCopies method of Collections class.

To create a List containing n copies of specified Object use static List nCopies(int n, Object obj) method of Java Collection class.This method returns immutable List containing n copies of the specified Object.
List Containing N copies of Specified Object_JavabynataraJ
import java.util.Collections;
import java.util.List;
import java.util.Iterator;

public class CreateListOfNCopiesExample {
 public static void main(String[] args) {
  List list = Collections.nCopies(5,"A");
  //iterate through newly created list
  System.out.println("List contains, ");
  Iterator itr = list.iterator();
  while(itr.hasNext())
  System.out.println(itr.next());
  }
    }

The Output of above program:

List contains,

    A
    A
    A
    A
    A

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.