Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize ArrayList with a range of integer values avoiding loops

Tags:

java

arraylist

I would like to initialize an ArrayList with a range of integer values. This is what I want to avoid:

ArrayList<Integer> numbers = new ArrayList<>();
for(int i = 0; i < x; i++){
    numbers.add(i);
}

I found rangeClosed function for IntStream:

IntStream.rangeClosed(0, instance.getNumVertices()-1);

But I think that the conversiont to ArrayList won't be worth it.

I'm looking for efficiency...

like image 392
scd Avatar asked Aug 22 '26 19:08

scd


1 Answers

The ArrayList is backed by an array. If you want to fill it with ascending values, you won't get any quicker than just iterating over those values and adding them to the list.

The only thing I'd change in your example is initialize the array with the already known size, so that it wouldn't spend time and memory on expansion of the underlying array:

ArrayList<Integer> numbers = new ArrayList<>(x);
for(int i = 0; i < x; i++){
    numbers.add(i);
}
like image 110
Sergei Avatar answered Aug 25 '26 08:08

Sergei