Java 如何使用迭代器遍历二维 ArrayList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21988341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:52:09  来源:igfitidea点击:

How to iterate through two dimensional ArrayList using iterator?

javaarraysarraylistiterator

提问by Zip

I would like to iterate through two dimensional ArrayListwhich includes Stringobjects 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 booleanvalue. How can I implement this in java?

我想遍历ArrayList包含String使用迭代器的对象的二维。我还想以某种方式进行迭代,让我选择是先使用boolean值进行水平(行)迭代还是垂直(列)迭代。我如何在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?

I don't know how I can implement the booleanvalue though.

我不知道如何实现该boolean值。

采纳答案by sakura

Row-wise iteration is simple as shown in the @Awfully Awesome answer.

如@Awfully Awesome 答案所示,逐行迭代很简单。

Tried a columnwise iteration with assumption that List will always have m cross nelements where m=n

尝试按列迭代,假设 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;
        }
    }
}

The answer uses Iterator.

答案使用迭代器。

回答by GameDroids

Maybe you need to implement two versions, with a booleanthat decides which loop to use:

也许你需要实现两个版本,一个boolean决定使用哪个循环:

public void iterate(boolean horizantalFirst){

    if(horizontalFirst){
        for(int i=0; i<array.size(); i++){              // first iterate through the "outer list"
            for(int j=0; j<array.get(i).size(); j++){   // then iterate through all the "inner lists"
                 array.get(i).get(j)="1";
            }
        }
    }else{ 
        int j=0;                            // index to iterate through the "inner lists"
        for(; j<array.get(j).size(); j++){   //dangerous, you need to be sure that there is a j-th element in array
            for(int i=0; i<array.size(); i++){  // iterate here through the outer list, by always working on the j-th element                
                array.get(i).get(j)="1";
            }
        }
    }
}

回答by Aman Agnihotri

Why not try this:

为什么不试试这个:

import java.util.ArrayList;

public class Iteration
{
  private ArrayList<ArrayList<String>> array;

  public Iteration()
  {
    array = new ArrayList<>();

    array.add(new ArrayList<String>());
    array.get(0).add("000");
    array.get(0).add("001");
    array.get(0).add("010");

    array.add(new ArrayList<String>());
    array.get(1).add("100");
    array.get(1).add("101");
    array.get(1).add("110");
    array.get(1).add("111");

    iterateRowWise();
    System.out.println("\n\n");

    iterateColumnWise();
  }

  public void iterateRowWise()
  {
    // This uses iterator behind the scene.
    for (ArrayList<String> row : array)
    {
      for (String element : row)
      {
        System.out.print(element + " ");
      }
      System.out.println();
    }
  }

  public void iterateColumnWise()
  {
    int arraySize = array.size();
    int maxColumns = getMaximumListSize();
    for (int c = 0; c < maxColumns; c++)
    {
      for (int r = 0; r < arraySize; r++)
      {
        ArrayList<String> rowList = array.get(r);
        if (c < rowList.size())
        {
          System.out.print(rowList.get(c) + " ");
        }
      }
      System.out.println();
    }
  }

  private int getMaximumListSize()
  {
    int maxListSize = 0;
    for (ArrayList<String> rowList : array)
    {
      if (maxListSize < rowList.size())
        maxListSize = rowList.size();
    }

    return maxListSize;
  }

  public static void main(String[] args)
  {
    new Iteration();
  }
}

The iterateRowWise()method iterates using the iterator, but it does so behind the scene.
The iterateColumnWise()method doesn't use iterator, but its safe to use.

iterateRowWise()方法使用迭代器进行迭代,但它是在幕后进行的。
iterateColumnWise()方法不使用迭代器,但使用起来很安全。