0

I want to unite two int arrays in Java. How can I improve the code? Maybe there is a function that already does that?

public class Unify{
    public static void main(String[] argv){
        int[] a = {1, 2, 3};
        int[] b = {4, 5, 6};
        int[] c = mylist(a, b);
        for (int x:c)
            System.out.println(x);
    }
    public static int[] mylist(int[] a, int[] b){
        int len = a.length + b.length;
        int[] c = new int[len];
        for(int i = 0; i < a.length; i++)
            c[i] = a[i];
        for(int i = a.length, j = 0; i < len; i++, j++)
            c[i] = b[j];
        return c;
    }
}

1 Answers1

1

In no particular order, you might use Arrays.toString(int[]) to print the result. And, Arrays.copyOf(int[], int)1 to create your new array and copy a. Finally, System.arraycopy(Object src, int srcPos, Object dest, int destPost, int length) to copy b into c. Something like,

public static void main(String[] argv) {
    int[] a = { 1, 2, 3 };
    int[] b = { 4, 5, 6 };
    int[] c = Arrays.copyOf(a, a.length + b.length);
    System.arraycopy(b, 0, c, a.length, b.length);
    System.out.println(Arrays.toString(c));
}

Output is (successfully indicating the copied array c)

[1, 2, 3, 4, 5, 6]

1The Javadoc says (in part) that copyOf returns a copy of the original array, truncated or padded with zeros to obtain the specified length

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249