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;
}
}
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.
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]+" ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With