rachel
rachel

Reputation: 63

Set an array value to another arrays value

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

Answers (4)

UNayak
UNayak

Reputation: 11

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

Upvotes: 0

Nidhish Krishnan
Nidhish Krishnan

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

Olimpiu POP
Olimpiu POP

Reputation: 5067

Use the utility class

java.util.Arrays

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

Upvotes: 1

Neil
Neil

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

Related Questions