java – System.arraycopy返回arrayoutofboundsexception
作者:互联网
我今天在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);
}
}
解决方法:
您的数组索引从0到[N-1],长度为(N),b数组索引从0到N,长度为(N 1),那么您必须编写System.arraycopy(a,0,b,1) ,N);
标签:java,arrays,arraycopy 来源: https://codeday.me/bug/20190828/1752190.html