如何使用迭代器遍历二维 ArrayList? [英] How to iterate through two dimensional ArrayList using iterator?
问题描述
我想使用迭代器遍历包含 String
对象的二维 ArrayList
.我还想通过使用 boolean
值来选择是先水平(行)还是垂直(列)迭代的方式进行迭代.我如何在 Java 中实现它?
I would like to iterate through two dimensional ArrayList
which includes String
objects using iterator. I also would like to iterate in a way that let me choose whether I want to iterate horizontally(row) first or vertically(column) by using a boolean
value. How can I implement this in java?
到目前为止我尝试过的.
What I've tried so far.
public class IterateThis implements Iterator<String>{
ArrayList<ArrayList<String>> array;
public IterateThis(){
array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
}
Iterator<String> it = array.iterator(); //This gives me an error...why?
我不知道如何实现 boolean
值.
I don't know how I can implement the boolean
value though.
推荐答案
行式迭代很简单,如@Awfully Awesome 答案所示.
Row-wise iteration is simple as shown in the @Awfully Awesome answer.
尝试按列迭代,假设 List 总是有 m cross n
元素,其中 m=n
Tried a columnwise iteration with assumption that List will always have m cross n
elements where m=n
public static void IterateThis() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
Iterator<ArrayList<String>> it = array.iterator();
int topLevelIteratorResetCounter = 0;
int noOfIteratorNextRequired = 1;
int size = array.size();
while (it.hasNext()) {
ArrayList<String> strList = it.next();
if (noOfIteratorNextRequired > strList.size())
break;
Iterator<String> itString = strList.iterator();
int numtimes = 0;
String str = null;
while (numtimes != noOfIteratorNextRequired) {
str = itString.next();
numtimes++;
}
System.out.println(str);
numtimes = 0;
topLevelIteratorResetCounter++;
if (topLevelIteratorResetCounter == size) { //as column count is equal to column size
it = array.iterator(); //reset the iterator
noOfIteratorNextRequired++;
topLevelIteratorResetCounter = 0;
}
}
}
答案使用迭代器.
这篇关于如何使用迭代器遍历二维 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!