mark
mark

Reputation: 62896

How to populate a list of generic lists in Java?

Observe the following code:

private List<List<Place>> m_grid = constructGrid(10000);

private static List<List<Place>> constructGrid(int size) {
  List<List<Place>> res = new ArrayList<List<Place>>(size);
  for (int i = 0; i < size; ++i) {
    res.add(null);
  }
  return res;
}

It is dull. Is there a prettier way to do the same thing? A one liner using some kind of a standard library?

Thanks.

EDIT

The list must be mutable. Hence, Collections.nCopies does not fit the bill.

Upvotes: 2

Views: 401

Answers (1)

beerbajay
beerbajay

Reputation: 20300

I don't really get why you need 10000 nulls in your list, but if you want to do this, you can do:

List<List<Place>> tmp = Collections.nCopies(10000, null); // immutable
List<List<Place>> res = new ArrayList<List<Place>>(tmp);  // mutable

Upvotes: 4

Related Questions