Search code examples
javaarraysarraylistfill

How to fill array or arraylist sequentially without loop?


I'm surprised I haven't found an answer to this anywhere. I want to fill an int array of 100 with 1..100. Fill is a good method but it doesn't increment the value each turn. Its obvious how to do it with a loop but I want to avoid that due to my maximum value being extremely high. Is there any api method which can do this for me?


Solution

    1. There is no method in the standard library that will do this.

    2. Even if there was, it would need to use a loop under the hood.

    3. I don't see the significance of "my maximum value being extremely high". That should make no difference to the decision to use a loop ... or not.

    4. Don't use recursion. Java does not implement tail call optimization so 1) it will be slower than using a loop and 2) you risk getting StackOverflowError if the array or list is large. (Yes, I know it is not large in the question as asked ...)