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!

4

2 回答 2

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};
于 2013-01-13T06:16:41.433 回答
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.

于 2013-01-13T06:18:52.190 回答