-1

My code is meant to combine two arrays into one larger array. The two arrays are accepted as arguments into a method, and the method adds the second one to the end of the first one, returning the result. For some reason, I'm getting an arrayIndexOutOfBoundsException. Can someone take a look at this and point out what I'm doing wrong? Thanks.

public static int[] merge(int[] a1, int[] a2) {
    int[] sum = new int[a1.length + a2.length];
    int x;

    for(x = 0; x < a1.length; x++) {
        sum[x] = a1[x];
    }
    for(int k = x; k < sum.length; k++) {
        sum[k] = a2[k];
    }
    return sum;
}
OCDkirby
  • 190
  • 9

1 Answers1

4
 for(int k = x; k < sum.length; k++)     sum[k] = a2[k]; // here

sum is larger then a2 so you are getting out of bounds exception

If you wanted to concate 2 arrays it would have to be something like that:

public static int[] merge(int[] a1, int[] a2) {
    int[] sum = new int[a1.length + a2.length];


    for(int x = 0; x < a1.length; x++) {
        sum[x] = a1[x];
    }
    for(int x=0; x < a2.length; x++) {
        sum[a1.length+x] = a2[x];
    }
    return sum;
}
Antoniossss
  • 31,590
  • 6
  • 57
  • 99