System.arraycopy返回arrayoutofboundsexception

时间:2017-05-17 03:28:44

标签: java arrays arraycopy

我今天学习了java中的arraycopy()函数,我在代码中使用它。但我经常得到一个ArrayOutOfBoundsException。我试图找出一个解决方案,并在谷歌搜索解决方案,但我似乎无法解决它。如果有人可以看一下它会很有帮助

System.arraycopy(a, 0, b, 1, N + 1);

这里,“a”是长度为“N”的数组,b是另一个长度为“N + 1”的数组 我希望将数组“a”的所有元素复制到数组“b”,使得数组“a”的所有元素都从数组“b”的第二个索引开始,为数组中的另一个元素留出空间“b”

以下是整个代码,如果有的话:

import java.util.Random;
import java.util.Scanner;

public class JavaApplication24 {

public static long DC;
public static long DM1;
public static long DM;

private static int[] Insrtn_sort(int[] a, int N) {

    int t, i;
    int b[] = new int[N + 1];
    DC = 0;
    DM = 0;
    DM1 = 0;

    b[0] = Integer.MIN_VALUE;
    System.arraycopy(a, 0, b, 1, N + 1);

    for (int j = 1; j < N + 1; j++) {
        t = b[j];
        i = j - 1;
        while (t < b[i]) {
            b[i + 1] = b[i];
            i--;
            DC++;
            DM1++;
        }
        b[j + 1] = t;
        DM++;
    }

    return b;
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Random r = new Random();
    float StartTime, EndTime, TotalTime;

    int N = sc.nextInt();
    int[] a = new int[N];
    for (int i = 0; i <= N - 1; i++) {
        a[i] = r.nextInt();
    }

    StartTime = System.currentTimeMillis() / 1000;
    Insrtn_sort(a, N);
    EndTime = System.currentTimeMillis() / 1000;

    TotalTime = StartTime - EndTime;

    for (int i = 1; i <= N - 1; i++) {
        System.out.println(a[i]);
    }
    System.out.println("Time taken for sorting: " + TotalTime);
    System.out.println("Total number of data comparisons: " + DC);
    System.out.println("Total number of data movements: " + DM + DM1);

}

}

2 个答案:

答案 0 :(得分:3)

您的void do1(int input) { do2(1); } 数组索引来自void do2(int input) { do1(2); } ,长度为(a),0 to [N-1]数组索引来自N,长度为({{1}那么你必须写b

答案 1 :(得分:2)

请参阅System.arraycopy源代码中的@param长度:

  

@param length要复制的数组元素的数量。

所以N + 1必须是N表示要复制的数字,就像数组的长度一样&#34; a&#34;

相关问题