java.lang.ArrayIndexOutOfBoundsException错误?

时间:2012-12-02 22:03:00

标签: java arrays indexoutofboundsexception arraycopy

我试图拆分一个数组,将一个部分存储在一个数组中,另一个部分存储在另一个数组中。然后我试图翻转2并将它们存储在一个新的数组中。这就是我所拥有的

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};

4 个答案:

答案 0 :(得分:1)

如果要访问范围[0,length - 1]之外的数组元素,则会得到ArrayIndexOutOfBoundsException;

如果您使用调试器,或者您可以自己找到问题 在每次调用System.arraycopy之前放置一个System.out.println(text),您可以在其中输出源和目标数组的数组长度以及要复制的元素数

答案 1 :(得分:0)

您的索引和数组长度已关闭:

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};

关键是要了解System.arraycopy不会复制最后一个索引的元素。

答案 2 :(得分:0)

摆脱不必要的索引操作:

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); 
}

答案 3 :(得分:0)

这一行错了:

System.arraycopy(a1, value+1, temp2, 0, a1.length-1);

您从第4位开始,想要复制9个元素。这意味着它试图将数组中索引4到12的元素复制。