JAN
JAN

Reputation: 21855

How to use the same iterator again and again?

Given the next code :

// this is a part of some large method //

        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).How can I place in humanPlayer the first element of the ArrayList after each time that I invoke makeSomeMove ?

(2).Is it possible to reuse an iterator ? since I use the hasnext() and next() ... ?

Many thanks Ron

Upvotes: 3

Views: 7795

Answers (3)

Bohemian
Bohemian

Reputation: 424983

Use an array Player[]. Unless you need to be able to conveniently make your list grow and shrink in size, using an array makes accessing any element at any time simple and readable.

Also, with an array you can still use the foreach syntax:

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

Upvotes: -1

Gus
Gus

Reputation: 6871

A simple iterator would be useless for that since it would be stuck at the final element. You want ListIterator so you can move it back to the start.

Edit: probably better not to try this however, as you will be unable to modify the list (if you do you will get a concurrent modification exception)

Upvotes: 0

Ravindra Gullapalli
Ravindra Gullapalli

Reputation: 9158

If you want to reuse the iterator, you have to re-initialise it.

You have to execute Iterator<String> iterator = players.iterator(); whenever you want to reuse the iterator.

Upvotes: 8

Related Questions