如何使用迭代器迭代二维ArrayList?

Zip*_*Zip 6 java arrays iterator arraylist

我想迭代二维ArrayList,包括String使用迭代器的对象.我还想以一种方式迭代,让我选择是否要通过使用boolean值水平(行)首先或垂直(列)迭代.我怎样才能在java中实现它?

到目前为止我尝试过的.

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?
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现这个boolean价值.

sak*_*ura 1

行式迭代很简单,如@Awously Awesome 答案所示。

尝试按列迭代,假设 List 始终具有m cross n其中的元素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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

答案是使用迭代器。