Reputation: 63
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];
}
Upvotes: 0
Views: 159
Reputation: 11
Use Arrays.copyOf method instead of taking burden of copying each element.
Upvotes: 0
Reputation: 20751
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 );
Upvotes: 1
Reputation: 5067
Use the utility class
java.util.Arrays
there are a bunch of copy methods. For instance copyOf or copyOfRange
Upvotes: 1
Reputation: 55432
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.
Upvotes: 1