I have a method attempting to transpose a ArrayList containing an ArrayList of string, called matrix and return the new array.
I found Transposing Values in Java 2D ArrayList, but it looks like it's for Arrays and not ArrayLists. My 2D array is of unknown dimensions, either rectangular or possibly irregular (but never square).
My idea was to read each inner array, and append the items to the inner arrays of the outgoing matrix.
public static ArrayList<ArrayList<String>> transpose (ArrayList<ArrayList<String>> matrixIn){
ArrayList<ArrayList<String>> matrixOut = new ArrayList<>();
//for each row in matrix
for (int r = 0; r < matrixIn.size(); r++){
ArrayList<String> innerIn = matrixIn.get(r);
//for each item in that row
for (int c = 0; c < innerIn.size(); c++){
//add it to the outgoing matrix
//get matrixOut current value
ArrayList<String> matrixOutRow = matrixOut.get(c);
//add new one
matrixOutRow.add(innerIn.get(c));
//reset to matrixOut
matrixOut.set(c,matrixOutRow);
}
}
return matrixOut;
}
I'm getting an "IndexOutOfBoundsException: Index: 0, Size: 0" error at
//get matrixOut[v]
ArrayList<String> matrixOutRow = matrixOut.get(v);
What am I doing wrong with this thing?
Copyright License:
Author:「the_dover」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/28057683/transpose-arraylistarrayliststring-in-java