Java:联合数组

时间:2016-02-07 01:58:46

标签: java

我想在Java中统一两个int数组。我该如何改进代码?也许有一个功能已经做到了?

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 个答案:

答案 0 :(得分:1)

无特定顺序,您可以使用Arrays.toString(int[])打印结果。并且,Arrays.copyOf(int[], int) 1 来创建新数组并复制a。最后,System.arraycopy(Object src, int srcPos, Object dest, int destPost, int length)b复制到c。像,

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));
}

输出(成功指示复制的数组c

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

1 Javadoc(部分)说copyOf 返回原始数组的副本,用零截断或填充以获得指定的长度