如何使用迭代器迭代二维ArrayList? [英] How to iterate through two dimensional ArrayList using iterator?
问题描述
我想迭代二维 ArrayList
,其中包含使用迭代器的 String
对象。我还想以一种方式迭代,让我选择是否要通过使用 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 $ c但是,$ c>值。
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跨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;
}
}
}
答案使用Iterator。
The answer uses Iterator.
这篇关于如何使用迭代器迭代二维ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!