1

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 (i.e. 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.

1
  • 1
    Multiply by 1.25 in order to make the array 25% larger. Right now you are making it smaller. Commented Feb 2, 2017 at 22:52

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I also just realized I had to multiply by 1.25 and not 0.25-- silly mistake. Thank you, it works now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.