1

In Java, is there any way to create a array of elements in range?

For example,

new int[] {1:10}, which should be equivalent to,
new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

I was thinking, if we need to create a array of large range elements (5-1000), rather than writing it like 5, 6, ..., 1000, if there is way like 5:1000.

unknown_boundaries
  • 1,292
  • 1
  • 18
  • 44

5 Answers5

8

In Java 8

int[] array = IntStream.rangeClosed(1, 10).toArray();
Reimeus
  • 155,977
  • 14
  • 207
  • 269
1

There is not a built-in language feature, but you can easily create a method that does it:

public static int[] createIntRangeArray(int start, int end) {
    int[] result = new int[end-start+1];
    for(int i = start; i <= end; i++)
        result[i-start] = i;
    return result;
}

and then:

createIntRangeArray(1, 10)
// is equivalent to
new int[] {1,2,3,4,5,6,7,8,9,10}
user253751
  • 50,383
  • 6
  • 45
  • 81
1
class ArrayGenerator {
    public static int[] generateArray(int start, int end) {
        int[] array = new int[end-start+1];
        for(int i=start;i<=end;i++) {
            array[i-start] = i;
        }
        return array;
    }
}

//this can be used like

    int start = 5;
    int end = 10;
    int[] generatedArray = ArrayGenerator.generateArray(start,end);

    for(int i : generatedArray) {
        System.out.println(i);
    }
Nielarshi
  • 1,106
  • 6
  • 10
1

Consider writing a separate method containing a loop which initializes your array.

public int[] createArrayWithRange(int startIncl, int endIncl) {
    int[] nums = new int[endIncl - startIncl + 1];
    for (int i = 0; i < (endIncl - startIncl + 1) ; i++) {
        nums[i] = i + startIncl;
    }
    return nums;
}
RuntimeException
  • 1,565
  • 2
  • 22
  • 30
0

My proposition:

public List<Integer> generateIntTab(int size){
        List<Integer> x = new ArrayList<Integer>();
        for(int i = 0 ; i < size; i++){
            x.add((i << 1)-i+1);
        }
        return x;
    }

Its a bit slower then standard JDK8 function which give @Reimeus

shutdown -h now
  • 445
  • 6
  • 18