如何一次又一次地使用相同的迭代器?

时间:2012-02-02 21:53:17

标签: java iterator

给出下一个代码:

//这是某个大型方法//

的一部分
        ArrayList<String> players = this.m_maze.getPlayers();

    // define the first node to be the human player , and pop him from the list 
    // the rest of the nodes are the computer side 

    Iterator<String> iterator = players.iterator();

    // human side 
    String humanPlayer = iterator.next();


    // controller - start a game between the players , at least two players are playing 
    while (this.m_rounds > 0)  
    {


        String[] choices = this.m_view.getChoiceFromUser();

        int usersChoice = Integer.parseInt(choices[0]);

        switch (usersChoice)
        {
            case 1:   // then user chose to stay put 
            {

            }

            case 2:   // then take the next step
            {
                // let the user make his move

                this.m_maze = this.m_model.makeSomeMove(choices[1],humanPlayer,true);

                // print out the maze for visualization
                this.m_view.drawMaze(m_maze);

                // controller - reduce the number of current rounds for the current game 
                this.m_rounds--; 
            }

            case 31:   // then user asked for the closest treasure
            {
                //  put some code here later on
            }


            case 32:   // then user asked for the nearest room 
            {
            //  put some code here later on
            }

        }  // end switch case

    } // end while 

(1)。每次调用humanPlayer后,如何将makeSomeMove放在ArrayList的第一个元素中?

(2)。是否可以重用迭代器?因为我使用hasnext()next() ...?

非常感谢 罗恩

3 个答案:

答案 0 :(得分:7)

如果要重用迭代器,则必须重新初始化它。

只要您想重用迭代器,就必须执行Iterator<String> iterator = players.iterator();

答案 1 :(得分:0)

一个简单的迭代器对它来说没用,因为它会被卡在最后一个元素上。您需要ListIterator,以便将其移回到开头。

编辑:最好不要尝试这个,因为你将无法修改列表(如果你这样做,你会得到一个并发修改异常)

答案 2 :(得分:-1)

使用数组Player[]。除非您需要能够方便地使列表的大小增大和缩小,否则使用数组可以随时访问任何元素,并且简单易读。

此外,使用数组,您仍然可以使用foreach语法:

Player[] players = new Player[9];
...
for (Player player : players) {
    // do something
}