0

I'm trying to write a merge method that takes three arrays and moves them into one. I'm quite new to java and the website where I'm submitting this code isn't very helpful with pointing out my error

static int[] mergeArrays(int[] a1, int[] a2, int[] a3) {

int[] answer = new int[a1.length + a2.length + a3.length];
int i,j,k;
for (i = 0; i < a1.length; i++)
    answer[i] = a1[i];

for (j = 0; j < a2.length; j++)
    answer[i++] = a2[j];

for (k = 0; k < a3.length; k++)
    answer[i++] = a3[k];

return answer;
}
STF
  • 1,485
  • 3
  • 19
  • 36
David Kane
  • 11
  • 1
  • 3
  • 6

2 Answers2

2

I do not see any benefit in writing a method that merges exactly three arrays. Please consider this more flexible signature:

public static int[] merge(int[]... intArrays);

Also low level loops and index manipulation should be avoided, Java 8 comes to help!

public static int[] merge(int[]... intArrays) {
    return Arrays.stream(intArrays)
            .flatMapToInt(i -> Arrays.stream(i))
            .toArray();
}

This is very concise, has no code duplication, no low level code and can even to be done in a parallel stream if arrays are large or many.

hata
  • 11,633
  • 6
  • 46
  • 69
martinhh
  • 336
  • 2
  • 10
0

List<Integer> mergedArray = Arrays.asList(array1); //will give you first list.

mergedArray.addAll(Arrays.asList(array2));
mergedArray.addAll(Arrays.asList(array3));
Rohith K
  • 1,433
  • 10
  • 15
  • 1
    This won't work since `Arrays.asList()` method returns a fixed-size list. So `.addAll()` method will throw an Exception – tfosra Jul 04 '16 at 08:19
  • 1
    You can take a look at this [post](http://stackoverflow.com/questions/16748030/difference-between-arrays-aslistarray-vs-new-arraylistintegerarrays-aslist) – tfosra Jul 04 '16 at 08:21