Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.arraycopy returning arrayoutofboundsexception

Tags:

java

arrays

I learnt about the arraycopy() function in java today and I was working with it in a code . But I was constantly getting an ArrayOutOfBoundsException. I tried to figure out a solution and searched on google for solutions but I can't seem to solve it. It would be helpful , if someone can take a look at it

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

Here, "a" is an array of length "N", and b is another array of length"N+1" I want to copy all the elements of array "a" to array "b" in such a way that , all the elements of array "a" are start from the 2nd index of array "b", leaving space for another element in array "b"

Here is the whole code if any requires it:

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

}

}
like image 957
Zarar Mahmud Avatar asked Jun 16 '26 15:06

Zarar Mahmud


2 Answers

Your a array Index is from 0 to [N-1] with length of(N) and b array index is from 0 to N with length of (N+1) then you must write System.arraycopy(a, 0, b, 1, N );

like image 151
Yashar Aliabbasi Avatar answered Jun 19 '26 05:06

Yashar Aliabbasi


See the @param length in the source of System.arraycopy:

@param length the number of array elements to be copied.

so the N+1 must be N means the number you want to copy, just as the length of array "a"

like image 25
zhenxianyimeng Avatar answered Jun 19 '26 04:06

zhenxianyimeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!