Transpose ArrayList > in Java
问题描述:
我有一个方法试图转置ArrayList包含一个ArrayList的字符串,名为矩阵并返回新的数组。我发现Transposing Values in Java 2D ArrayList,但它看起来像是数组而不是ArrayList。我的2D阵列具有未知尺寸,可能是矩形或可能不规则(但从不是方形)。Transpose ArrayList <ArrayList <String>> in Java
我的想法是读取每个内部数组,并将这些项追加到输出矩阵的内部数组中。
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:指数:0,大小:0” 错误在
//get matrixOut[v]
ArrayList<String> matrixOutRow = matrixOut.get(v);
我在做什么不对的事吗?
答
假设:每个内部列表都有相同的元素数目。这可以帮助你。
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;
}
+0
感谢您的帮助,但我不能认为内部数组将具有相同的长度。你的变量名称的确让我想到了构建一个消除锯齿状数组的方法 - 但是最终导致出现了一些尝试/捕获超出界限的错误。新代码将在下面发布。 – 2015-01-23 20:52:11
答
在这里回答我自己的问题。这是我现在正在做的:
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。所以,现在我只需找到最大尺寸并通过添加“”来捕捉所有超出界限的错误。
我敢肯定,有一种更清洁的方式,但这似乎工作。
'size:0'表示列表中没有元素。 – 2015-01-21 00:35:27
这是编译? ArrayList> matrixOut = new ArrayList ();和matrixOut是空列表 –
nayakam
2015-01-21 00:43:01