1

I want to assign integers 1-10 to already existing integer array first 10 values (index 0-9). Is there way to do this quickly without for loop or do I need for loop?

Example:

//already existing array with index 0-14.
//want to change this to {1,2,3,4,5,6,7,8,9,10,1,1,1,1,1}
int[] array = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);

What I know:

int x = 1;
for (int a = 0; a < 10; a++)
{
    array[a] = x;
    x++;
}

Is there faster way, some command perhaps?

Thanks!

nemesv
  • 138,284
  • 16
  • 416
  • 359
John Smith
  • 15
  • 4
  • 1
    *"Is there faster way,"* 99% of the time, code clarity is more important than speed. If the app. begins to bog down, check it using a profiler to check exactly where the bottleneck is. The results are usually surprising. – Andrew Thompson Jan 13 '13 at 08:07

2 Answers2

3

You could statically assign it, it is cleaner if you have static data

int[] array = {1,2,3,4,5,6,7,8,9,10};
jmj
  • 237,923
  • 42
  • 401
  • 438
  • @JohnSmith use another variable name something like myarray – someone Jan 13 '13 at 06:59
  • John, I am not completely following you, if you want to create fixed size array with default value initialized (1...10), follow my answer, if you want to edit those value you still can edit by assigning value to array index like `arr[i] = someValue;` – jmj Jan 13 '13 at 07:18
  • for declaration time initialization you should prefer the way I suggested if the initial values are static, if you want to change it later you could still use loop, it depends on how long your array is, for 10 sized array it will not make much difference – jmj Jan 13 '13 at 07:25
  • `System.arrayCopy()` [is absolutely better , it uses `memcopy`](http://stackoverflow.com/questions/2772152/why-is-system-arraycopy-native-in-java), but you could copy array to another one, so it really depends if you have the array available which is going to be copied, Please read javadoc for it to troubleshoot why it is not working – jmj Jan 13 '13 at 07:34
  • Hi John, Your this behavior is SPAM considering SO's scope, Please follow guidelines you were given while registering account and you would be good – jmj Jan 13 '13 at 09:05
2

You can create a static constant array of ten elements, and then copy it in place with System.arrayCopy.

static int[] template = new int[]{1,2,3,4,5,6 7,8,9,10};

System.arrayCopy(template, 0, dest, 0, 10);

The remaining elements of the dest array will remain intact.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523