If your input looks like this:
[ [ 1, 2 ],
[ 3, 4, 5, 6 ],
[ 7 ] ]
The transposed result could be one of these:
SIMPLE COMPACT
[ [ 1, 3, 7 ], [ [ 1, 3, 7 ],
[ 2, 4, null ], [ 2, 4 ],
[ null, 5, null ], [ null, 5 ],
[ null, 6, null ] ] [ null, 6 ] ]
In either case, the result should have as many columns as the longest row, not the first row.
public static Object[][] transposeSimple(Object[][] data) {
int maxLen = 0;
for (Object[] row : data)
if (row.length > maxLen)
maxLen = row.length;
Object[][] temp = new Object[maxLen][data.length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[i].length; j++)
temp[j][i] = data[i][j];
return temp;
}
public static Object[][] transposeCompact(Object[][] data) {
int maxLen = 0;
for (Object[] row : data)
if (row.length > maxLen)
maxLen = row.length;
Object[][] temp = new Object[maxLen][];
for (int i = 0; i < temp.length; i++) {
for (maxLen = data.length; maxLen > 0; maxLen--)
if (data[maxLen - 1].length > i)
break;
temp[i] = new Object[maxLen];
for (int j = 0; j < maxLen; j++)
if (i < data[j].length)
temp[i][j] = data[j][i];
}
return temp;
}
Test
System.out.println(Arrays.deepToString(transposeSimple(new Object[][] {
{ 1, 2 },
{ 3, 4, 5, 6 },
{ 7 },
})));
System.out.println(Arrays.deepToString(transposeCompact(new Object[][] {
{ 1, 2 },
{ 3, 4, 5, 6 },
{ 7 },
})));
Output
[[1, 3, 7], [2, 4, null], [null, 5, null], [null, 6, null]]
[[1, 3, 7], [2, 4], [null, 5], [null, 6]]
Object[][] temp, and you're missing a semi-colon afterdata[i][j].