Reputation: 11
Im trying to split an array, store one part in one array and the other part in another array. Then im trying to flip the 2 and store them in a new array. here is what i have
public int[] flipArray(){
int value = 3;
int[] temp1 = new int[value];
int[] temp2 = new int[(a1.length-1) - (value+1)];
int[] flipped = new int[temp1.length+temp2.length];
System.arraycopy(a1, 0, temp1, 0, value);
System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
System.arraycopy(temp2, 0, flipped, 0, temp2.length);
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length);
return flipped;
}
private int[]a1={1,2,3,4,5,6,7,8,9,10};
Upvotes: 0
Views: 1986
Reputation: 433
This line is wrong:
System.arraycopy(a1, value+1, temp2, 0, a1.length-1);
You start from position 4 and want to copy 9 elements. That means it tries to copy elements from index 4 to 12 in the array.
Upvotes: 0
Reputation: 28727
You get the ArrayIndexOutOfBoundsException when you want to access an array element outside the range [0, length - 1];
You can find the probelm yourself, if you either use the debugger, or place a System.out.println(text) before each call of System.arraycopy where you output the array length of the source and destination array and the number of elements to copy
Upvotes: 1
Reputation: 3710
get rid of unnecessary manipulations with indexes:
public int[] flipArray(){
int value = 3;
int[] temp1 = new int[value];
int[] temp2 = new int[a1.length - value];
int[] flipped = new int[temp1.length+temp2.length];
System.arraycopy(a1, 0, temp1, 0, value);
System.arraycopy(a1, value, temp2, 0, temp2.length);
System.arraycopy(temp2, 0, flipped, 0, temp2.length);
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length);
}
Upvotes: 0
Reputation: 234795
Your indexing and array lengths are off:
public int[] flipArray(){
int value = 3;
int[] temp1 = new int[value];
int[] temp2 = new int[a1.length - value];
int[] flipped = new int[a1.length];
System.arraycopy(a1, 0, temp1, 0, value);
System.arraycopy(a1, value, temp2, 0, temp2.length);
System.arraycopy(temp2, 0, flipped, 0, temp2.length);
System.arraycopy(temp1, 0, flipped, temp2.length, temp1.length);
return flipped;
}
private int[]a1={1,2,3,4,5,6,7,8,9,10};
The key is to understand that System.arraycopy
does not copy the element at the last index.
Upvotes: 0