0

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};
  • 2
    Hi, please can you post the exception message as it will tell us which line the code is giving an array index out of bounds error. – ThePerson Dec 02 '12 at 22:05
  • possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Raedwald Apr 01 '15 at 22:40

4 Answers4

1

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

AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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); 
}
bellum
  • 3,642
  • 1
  • 17
  • 22
0

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.

andreih
  • 423
  • 1
  • 6
  • 19