计算数组的大小

时间:2014-09-04 02:38:43

标签: java arrays for-loop

我想创建一个大小为n的数组,其中n由循环变量定义,但我不知道如何预先计算数组的大小。 我们可以假设开始&lt; <结束和步骤> 0

int start; // Initialized by user
int end; // Initialized by user
int step; // Initialized by user

int size = ? // What is the formula for the size ?

Object[] array = new Object[size];
int index=0;

for(int i=start; i<=end; i+=step){
    array[index++]=new Object();
}

我可以使用List然后将元素复制到数组中,但这似乎是绕道而行。

:(结束 - 开始)/尺寸

1 个答案:

答案 0 :(得分:0)

int size = ceiling(float(end - start + 1)/size);

您需要添加1,因为您使用i <= end,因此必须包含结束值。

相关问题