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.
You are looking for Collections.nCopies(int, T)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With