2013-02-01 81 views
3

我有這個從excel文件獲取信息的小腳本。收集完我需要的信息後,我想將這兩個數組合併成一個。那可能嗎?如何在Java中組合兩個對象數組

public Object[][] createData1() throws Exception { 
    Object[][] retObjArr1 = data.getTableArray("C:\\Users\\OAH\\Workspaces\\Chrome2\\Testdata2.xls", "Sheet1", "normalCustomer"); 
    Object[][] retObjArr2 = data.getTableArray("C:\\Users\\OAH\\Workspaces\\Chrome2\\Testdata2.xls", "Sheet2", "langLogin"); 
    return(retObjArrCombined); //I want to return one array with both arrays 
} 
+0

是否允許重複在數組中的元素工會? – alepuzio

+1

看到這個問題:http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java – BlairHippo

+1

除非沒有人想過在你之前合併兩個數組,否則我很確定Google使用' java merge arrays'會給你你正在尋找的答案。 – sp00m

回答

3

您可以使用System.arraycopy方法(是,全部小寫)。 Javadoc。你可以使用java.util.Arrays類來做更多的東西。

2

這個怎麼樣?

Link to Another Stack Question!!!!!!

public static int[][] append(int[][] a, int[][] b) { 
    int[][] result = new int[a.length + b.length][]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result; 
} 
0

另一種方式:

Object[][] one = {{1, 2, 3}, {4, 5}, {6}}; 
Object[][] two = {{7, 8}, {9}}; 
List<Object[]> holder = new ArrayList<>(); 

Collections.addAll(holder, one); 
Collections.addAll(holder, two); 

Object[][] result = holder.toArray(new Object[holder.size()][]); 
0

下面的代碼實現您的任務:

Object[][] retObjArr1 = { { "a00", "a01" }, { "a10", "a11" }, 
     { "a20", "a21" } }; 
Object[][] retObjArr2 = { { "b00", "b01" }, { "b10", "b11" }, 
     { "b20", "b21" } }; 

List<Object[][]> list = new ArrayList<Object[][]>(); 
list.add(retObjArr1); 
list.add(retObjArr2); 

int totalRow = 0; 
for (int all = 0; all < list.size(); all++) { 
    totalRow += list.get(all).length; 
} 
Object[][] retObjArrCombined = new Object[totalRow][]; 
int rowCount = 0; 
for (int all = 0; all < list.size(); all++) { 
    Object[][] objects = list.get(all); 
    for (int i = 0; i < objects.length; i++) { 
     retObjArrCombined[rowCount] = objects[i]; 
     rowCount++; 
    } 
} 
for (int i = 0; i < retObjArrCombined.length; i++) { 
    for (int j = 0; j < retObjArrCombined[i].length; j++) { 
     System.out.println("value at :(" + i + "," + j + ") is:" 
       + retObjArrCombined[i][j]); 
    } 
} 

在這段代碼中,Object[][] retObjArrCombined包含retObjArr1複製所有陣列,retObjArr2等...它輸出以下:

value at :(0,0) is:a00 
value at :(0,1) is:a01 
value at :(1,0) is:a10 
value at :(1,1) is:a11 
value at :(2,0) is:a20 
value at :(2,1) is:a21 
value at :(3,0) is:b00 
value at :(3,1) is:b01 
value at :(4,0) is:b10 
value at :(4,1) is:b11 
value at :(5,0) is:b20 
value at :(5,1) is:b21 
1

下面是簡單的解決方案:

private static Object[] concatenate(Object[] a, Object[] b) { 
    Collection<Object> result = new ArrayList<Object>(a.length + b.length); 
    for (Object val : a) { 
     result.add(val); 
    } 
    for (Object val : b) { 
     result.add(val);    
    } 
    return result.toArray(); 
} 
相關問題