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?
我很惊讶我在任何地方都找不到答案。我想用1..100填充100的int数组。填充是一种很好的方法,但它不会在每个回合中增加值。很明显如何使用循环,但我想避免这种情况,因为我的最大值非常高。有没有api方法可以为我做这个?
2 个解决方案
#1
8
-
There is no method in the standard library that will do this.
标准库中没有方法可以执行此操作。
-
Even if there was, it would need to use a loop under the hood.
即使有,也需要在引擎盖下使用一个循环。
-
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.
我没有看到“我的最大价值极高”的意义。这对使用循环的决定没有任何影响......或者不是。
-
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
*Error
if the array or list is large. (Yes, I know it is not large in the question as asked ...)不要使用递归。 Java没有实现尾调用优化,因此1)它比使用循环慢,2)如果数组或列表很大,你可能会遇到*Error。 (是的,我知道问题并不大......)
#2
0
Ooooh, use recursion!
哦,使用递归!
void to100(int[] array, int i, int v) {
if( i < array.length ) {
array[i] = v;
to100( i+1, v+1 );
}
}
int[] array = new int[100];
too100( array, 0, 1 );
enjoy.
请享用。
#1
8
-
There is no method in the standard library that will do this.
标准库中没有方法可以执行此操作。
-
Even if there was, it would need to use a loop under the hood.
即使有,也需要在引擎盖下使用一个循环。
-
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.
我没有看到“我的最大价值极高”的意义。这对使用循环的决定没有任何影响......或者不是。
-
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
*Error
if the array or list is large. (Yes, I know it is not large in the question as asked ...)不要使用递归。 Java没有实现尾调用优化,因此1)它比使用循环慢,2)如果数组或列表很大,你可能会遇到*Error。 (是的,我知道问题并不大......)
#2
0
Ooooh, use recursion!
哦,使用递归!
void to100(int[] array, int i, int v) {
if( i < array.length ) {
array[i] = v;
to100( i+1, v+1 );
}
}
int[] array = new int[100];
too100( array, 0, 1 );
enjoy.
请享用。