简体   繁体   English

Java:前n个整数的数组

[英]Java: Array of first n integers

Any shortcut to create a Java array of the first n integers without doing an explicit loop? 在不进行显式循环的情况下创建前n个整数的Java数组的任何快捷方式? In R, it would be 在R中,它会

intArray = c(1:n) 

(and the resulting vector would be 1,2,...,n). (并且得到的矢量将是1,2,...,n)。

If you're using , you could do: 如果你使用的是 ,你可以这样做:

int[] arr = IntStream.range(1, n).toArray();

This will create an array containing the integers from [0, n) . 这将创建一个包含[0, n)整数的数组。 You can use rangeClosed if you want to include n in the resulting array. 如果要在结果数组中包含n ,可以使用rangeClosed

If you want to specify a step, you could iterate and then limit the stream to take the first n elements you want. 如果要指定步骤,可以iterate然后limit流以获取所需的前n元素。

int[] arr = IntStream.iterate(0, i ->i + 2).limit(10).toArray(); //[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Otherwise I guess the simplest way to do is to use a loop and fill the array. 否则我想最简单的方法是使用循环并填充数组。 You can create a helper method if you want. 如果需要,可以创建辅助方法。

static int[] fillArray(int from, int to, int step){
    if(to < from || step <= 0)
        throw new IllegalArgumentException("to < from or step <= 0");

    int[] array = new int[(to-from)/step+1];
    for(int i = 0; i < array.length; i++){
        array[i] = from;
        from += step;
    }
    return array;
}
...
int[] arr3 = fillArray(0, 10, 3); //[0, 3, 6, 9]

You can adapt this method as your needs to go per example from an upperbound to a lowerbound with a negative step. 您可以根据需要调整此方法,从上行到下行,并使用负步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM