簡體   English   中英

如何在Java中拼接二維arrays

[英]How to concatenate two-dimensional arrays in Java

我有一種情況需要連接兩個二維arrays。

Object[][] getMergedResults() {
    Object[][] a1 = getDataFromSource1();
    Object[][] a2 = getDataFromSource2();
    // I can guarantee that the second dimension of a1 and a2 are the same
    // as I have some control over the two getDataFromSourceX() methods

    // concat the two arrays
    List<Object[]> result = new ArrayList<Object[]>();
    for(Object[] entry: a1) {
        result.add(entry);
    }
    for(Object[] entry: a2) {
        result.add(entry);
    }
    Object[][] resultType = {};

    return result.toArray(resultType);
}

我在這篇文章中查看了連接一維 arrays 的解決方案,但無法使其適用於我的二維 arrays。

到目前為止,我提出的解決方案是遍歷 arrays 並將每個成員添加到 ArrayList,然后返回該數組列表的 toArray()。 我確信一定有一個更簡單的解決方案,但到目前為止還無法提供一個。

你可以試試

Object[][] result = new Object[a1.length + a2.length][];

System.arraycopy(a1, 0, result, 0, a1.length);
System.arraycopy(a2, 0, result, a1.length, a2.length);

您可以使用Apache Commons Library - ArrayUtils 僅更改第二維的索引並合並整行。

這是我用於2D數組連接的方法。 它部分使用了Sergio Nakanishi的答案,但增加了兩個方向連接的能力。

/*
 * Define directions for array concatenation
 */
public static final byte ARRAY_CONCAT_HORIZ = 0, ARRAY_CONCAT_VERT = 1;

/*
 * Concatenates 2 2D arrays
 */
public static Object[][] arrayConcat(Object[][] a, Object[][] b, byte concatDirection)
{
    if(concatDirection == ARRAY_CONCAT_HORIZ && a[0].length == b[0].length)
    {
        return Arrays.stream(arrayConcat(a, b)).map(Object[].class::cast)
                    .toArray(Object[][]::new);
    }
    else if(concatDirection == ARRAY_CONCAT_VERT && a.length == b.length)
    {
        Object[][] arr = new Object[a.length][a[0].length + b[0].length];
        for(int i=0; i<a.length; i++)
        {
            arr[i] = arrayConcat(a[i], b[i]);
        }
        return arr;
    }
    else
        throw new RuntimeException("Attempted to concatenate arrays of incompatible sizes.");
}

/*
 * Concatenates 2 1D arrays
 */
public static Object[] arrayConcat(Object[] a, Object[] b)
{
    Object[] arr = new Object[a.length + b.length];
    System.arraycopy(a, 0, arr, 0, a.length);
    System.arraycopy(b, 0, arr, a.length, b.length);
    return arr;
}

邏輯方式-

    for(int j = 0; j < a.length+b.length; j++){
        if(j < a.length){
            ans[j] = a[j];
        }else{
            ans[j] = b[j-(a.length)];
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM