我有一个方法试图转换一个包含字符串的ArrayList (称为矩阵)的ArrayList并返回新的数组。
我找到了Transposing Values in Java 2D ArrayList,但是看起来它是用于数组而不是ArrayLists的。我的二维数组是未知尺寸的,要么是矩形的,要么是不规则的(但绝不是正方形)。
我的想法是读取每个内部数组,并将这些项附加到传出矩阵的内部数组中。
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;
}我得到一个"IndexOutOfBoundsException: Index: 0,Size: 0“错误
//get matrixOut[v]
ArrayList<String> matrixOutRow = matrixOut.get(v);我这东西怎么了?
发布于 2015-01-23 20:59:35
在这里回答我自己的问题。这就是我现在要做的
public static ArrayList<ArrayList<String>> transpose (ArrayList<ArrayList<String>> matrixIn){
ArrayList<ArrayList<String>> matrixOut = new ArrayList<>();
int rowCount = matrixIn.size();
int colCount = 0;
//find max width
for(int i = 0; i < rowCount; i++){
ArrayList<String> row = matrixIn.get(i);
int rowSize = row.size();
if(rowSize > colCount){
colCount = rowSize;
}
}
//for each row in matrix
for (int r = 0; r < rowCount; r++){
ArrayList<String> innerIn = matrixIn.get(r);
//for each item in that row
for (int c = 0; c < colCount; c++){
//add it to the outgoing matrix
//get matrixOut[c], or create it
ArrayList<String> matrixOutRow = new ArrayList<>();
if (r != 0) {
try{
matrixOutRow = matrixOut.get(c);
}catch(java.lang.IndexOutOfBoundsException e){
System.out.println("Transposition error!\n"
+ "could not get matrixOut at index "
+ c + " - out of bounds" +e);
matrixOutRow.add("");
}
}
//add innerIn[c]
try{
matrixOutRow.add(innerIn.get(c));
}catch (java.lang.IndexOutOfBoundsException e){
matrixOutRow.add("");
}
//reset to matrixOut[c]
try {
matrixOut.set(c,matrixOutRow);
}catch(java.lang.IndexOutOfBoundsException e){
matrixOut.add(matrixOutRow);
}
}
}
return matrixOut;
}我不能假设数组是光滑的,我仍然希望返回一个嵌套的ArrayList。所以现在我只是找到最大维数,并通过添加"“来捕捉所有的界外错误。
我肯定有更干净的方法,但这似乎很有效。
发布于 2015-01-21 00:57:29
假设:每个内部列表都有相同的元素。这能帮到你。
public static List<List<String>> transpose(ArrayList<ArrayList<String>> matrixIn) {
List<List<String>> matrixOut = new ArrayList<List<String>>();
if (!matrixIn.isEmpty()) {
int noOfElementsInList = matrixIn.get(0).size();
for (int i = 0; i < noOfElementsInList; i++) {
List<String> col = new ArrayList<String>();
for (List<String> row : matrixIn) {
col.add(row.get(i));
}
matrixOut.add(col);
}
}
return matrixOut;
}https://stackoverflow.com/questions/28057683
复制相似问题