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

JAN*_*JAN 3 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 
Run Code Online (Sandbox Code Playgroud)

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

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

非常感谢罗恩

Rav*_*lli 8

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

Iterator<String> iterator = players.iterator();每当要重用迭代器时都必须执行.

  • 这不会重用迭代器,它只是重用变量.`iterator()`int ArrayList调用`return new Itr();`.如果不扩展ArrayList,则不能重用迭代器的相同实例. (3认同)