1

I am relatively new to Java programming and am trying to create an array with values from (2017 - 3017).

I was wondering if there is a way to create an array and have it pre-filled with these values so instead of doing:

int[] anArray = {2017, 2018, 2019, 2020... 3017}

which seems extremely long-winded, I can simply define a range of integers I wish to add to the array.

I know there are similar question to this one on the site, however none of them have answers that help me.

Thanks!

Edit: I forgot to mention I am using Java 7 and therefore cannot use IntStream.

2 Answers2

6

How about this:

int[] anArray = IntStream.rangeClosed(2017, 3017).toArray(); //closed includes upper bound

Java 7 would simply require a loop to fill the array:

int min = 2017, max = 3017;
int count = max - min + 1; //we're including upper bound
int[] anArray = new int[count];
for (int i = 0; i < count; i++, min++) {
    anArray[i] = min; //reused and incremented min
}
Rogue
  • 11,105
  • 5
  • 45
  • 71
0

Well it is answered. But just to point out another way in java .. you can count the number of integers that will be coming and use iterator to fill the array.Let me know if you have any doubts in this In short I am saying to do like the following:

 int arr[] = new int[1001];
for(int i=2017;i<=3017;i++){
  arr[i-2017]=i;
} 
Yash Jain
  • 55
  • 1
  • 9