Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to initialize an arraylist

Tags:

java

arrays

loops

I want an Arraylist in Java, which I want to fill with 10's

ArrayList<Integer> list = new ArrayList<Integer>(100);
for (int i = 0; i < 100; i++) {
    list.add(10);
}

I'm going to have to initialize a lot of Arraylists, so I was wondering if there is there a clean way to do this without a for loop?

like image 339
Kimberly Kim Avatar asked Jul 19 '26 10:07

Kimberly Kim


1 Answers

You can use Collections.nCopies:

ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 10));

This will initialize list with 100 10's.

like image 154
jh314 Avatar answered Jul 20 '26 23:07

jh314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!