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...
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);
}
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