简体   繁体   中英

Java: System.arraycopy for 2 parts of array

Suppose I have an array declared as

int[] unordered = {3, 4, 5, 1, 2};

and I want to create a new array, a, with a size 25% greater than that of unordered which has the original contents in order, followed by the indices that have not yet been assigned a value (ie 1, 2, 3, 4, 5, 0, 0, 0). How would I do this using System.arraycopy? Currently, what I have is:

int[] a = new int[(int)(unordered.length*.25)];
System.arraycopy(items, 3, a, 0, unordered.length-3);
System.arraycopy(items, 0, a, unordered.length-3, 3);

When I run this code, I get an array out of bounds error.

Change this:

int[] a = new int[(int)(unordered.length*.25)];

To:

int[] a = new int[(int)(unordered.length*1.25) + 1];

As int cast is lowering the number (for example 3.5 -> 3 etc.) you should add one to the array size.

Also multiply by 1.25 in order to increase the array size as multiply by 0.25 is decreasing the size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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