How to concatenate two arrays of objects in Java
I have this little script that gets information from an excel file. After I have gathered the information that I need, I want to combine these two arrays into one. Is it possible?
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
}
+3
source to share
5 answers
How about this?
Link to another question on the stack !!!!!!
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;
}
+2
source to share
The following code accomplishes your task:
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]);
}
}
This code Object[][] retObjArrCombined
contains all the arrays copied from retObjArr1
, retObjArr2
etc ... And it prints the following output:
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
0
source to share