Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Initialize collection (list) of size n > 1 with the same elements

I would like to have a one-liner in Java like this:

List<A> list = initialize(element, n);

where element is of type A and n is an integer representing the wished size of the collection.

My original problem was to fill the list with the same reference without making copies of element, but also with copying is a good compromise.

Apache or Google collection utilities or similar are welcome. And if you think that this can be generalized to other java collections than lists, please add your comments.

Up to now that's my best solution (A is Boolean):

Lists.newArrayList(Arrays.copyOf(new Boolean[ ] { false }, n))

I found a similar question (not on hold or closed) but it is not for java.

like image 624
Gismo Ranas Avatar asked Oct 21 '13 19:10

Gismo Ranas


1 Answers

You are looking for Collections.nCopies(int, T).

like image 77
Jeffrey Avatar answered Sep 20 '22 23:09

Jeffrey