Java数组连接问题

时间:2015-01-15 11:15:09

标签: java arrays arraylist merge concatenation

我试图融合两个数组,第二个数组偏移1:

String [] array1 = {"1", "2", "3", "4");
String [] array2 = {"my", "name", "is", "max");

我希望输出为:

1 my 2 name 3 is 4 max

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果两个数组的长度相同,只需使用:

    for (int i = 0; i < array1.length; i++) {
        System.out.print(array1[i] + " " + array2[i] + " ");
    }

但也许您应该考虑更改数据结构而不是使用两个数组。

答案 1 :(得分:0)

这段代码应该适用于每个数组长度:

public static void main(String args[]) {
    String[] a = {"1", "2", "3"};
    String[] b = {"hello", "how", "are", "you", "?"};

    String[] merged = merge(a, b);
}

public static String[] merge(String[] a, String[] b) {
    int i = 0;
    int j = 0;
    int k = 0;

    String[] merge = new String[a.length + b.length];

    while (i < a.length && j < b.length) {
        merge[k++] = a[i++];
        merge[k++] = b[j++];
    }
    while (i < a.length)
        merge[k++] = a[i++];
    while (j < b.length)
        merge[k++] = b[j++];

    return merge;
}

输出:

1
hello
2
how
3
are
you
?