0

I have two arrays, and I am trying to copy the array values from one to the other, but not all of them. Here is the code that I have. I am getting an error on the line with finalplace[y] = place[y];. I have another array called place, which is the longer array. I do not want to make an exact copy of the place array. I just want to get the first array values where their placement is less than count. Any ideas?

int [] finalplace = new int [count];
for (int y = 0; y <= count; y = y + 1) {
    finalplace[y] = place[y];
}
0

4 Answers 4

1

The indices of your new array range up to, but not including, count. So you should do the same with your for loop.

Note that System.arraycopy will let you copy part of an array.

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

Comments

1

Use the utility class

java.util.Arrays

there are a bunch of copy methods. For instance copyOf or copyOfRange

Comments

1

You can try using System.arraycopy()

int[] a = new int[]{1,2,3,4,5};
int[] b = new int[5];

System.arraycopy( a, 0, b, 0, a.length );

Comments

0

Use Arrays.copyOf method instead of taking burden of copying each element.

Comments

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.