Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two integer arrays into one array in java

Tags:

java

arrays

I've seen similar questions and none provide the answer that I'm looking for, so I apologize in advance if this is considered a duplicate. I'm trying to combine arrays {1, 2, 3} and {4, 5, 6} into {1, 2, 3, 4, 5, 6}. What am I doing incorrectly? I'm super new to java. Sorry if the question is stupid.

public class combine {
  public static void main(String[]args){

  int[]a = {1, 2, 3};
  int[]b = {4, 5, 6};
  int[]c = new int[a+b];
  for(int i=0; i<a.length; i++)
  System.out.print(c[i]+" ");
}
public static int[]merge(int[]a, int[]b){
  int[]c = new int[a.length+b.length];
  int i;
  for(i=0; i<a.length; i++)
     c[i] = a[i];

     for(int j=0; j<b.length; j++)
        c[i++]=b[j];
        return c;
}
}
like image 947
Jeremy Stone Avatar asked Nov 30 '22 02:11

Jeremy Stone


2 Answers

Don't do it yourself, use System.arrayCopy() to copy both arrays into a new array of the combined size. That's much more efficient, as it uses native OS code.

like image 150
Sean Patrick Floyd Avatar answered Dec 05 '22 11:12

Sean Patrick Floyd


Instead of

int[]c = new int[a+b];

You need to call your merge method and assign the result to the array like :

int[]c = merge(a,b);

Also you for loop should be :

int[]c = merge(a,b);
for(int i=0; i<c.length; i++)
    System.out.print(c[i]+" ");
like image 23
Alexis C. Avatar answered Dec 05 '22 12:12

Alexis C.