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
Please try this code, I hope it's useful for you
String a[] = new String[4];
String b[] = new String[2];
String[] ab = new String[a.length + b.length];
int i, j, d, s = 0;
@SuppressWarnings("resource")
Scanner x = new Scanner(System.in);
System.out.println("Enter the first array");
for (i = 0; i < a.length; i++) {
a[i] = x.next();
for (d = i; d < a.length; d++) {
ab[d] = a[i];
}
}
System.out.println("Enter the second array");
for (j = 0; j < b.length; j++) {
b[j] = x.next();
for (d = a.length + j; d < ab.length; d++)
ab[d] = b[j];
}
System.out.println();
System.out.println("The new array is !!");
System.out.println("--------------------");
for (s = 0; s < ab.length; s++) {
System.out.print(ab[s] + " ");
}
One more way of concatenating 2 arrays is:
System.out.println("Enter elements for a: ");
for (int i = 0; i < 5; i++) {
int num = in.nextInt();
a[i] = num;
}
System.out.println("Enter elements for b: ");
for (int i = 0; i < 5; i++) {
int num = in.nextInt();
b[i] = num;
}
void merge() {
int c[] = new int[10];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
System.out.println(Arrays.toString(c)); // merged array
}
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]+" ");
public static void main(String[]args){
int[]a = {1, 2, 3};
int[]b = {4, 5, 6};
int[]c ;
c=merge(a,b);
for(int i=0; i<c.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];
System.out.println(i);
for(int j=0; j<b.length; j++)
c[i++]=b[j];
return c;
}
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));