Java Collection How to - Fill n Copies of Specified Object to a List








Question

We would like to know how to fill n Copies of Specified Object to a List.

Answer

//from w w  w. jav a  2 s  .  co  m
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

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

The code above generates the following result.