How to use the same iterator again and again?

前端 未结 3 1603
攒了一身酷
攒了一身酷 2020-12-21 07:16

Given the next code :

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

        ArrayList players = this.m_maze.getPlayers();

    // define          


        
相关标签:
3条回答
  • 2020-12-21 07:55

    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)

    0 讨论(0)
  • 2020-12-21 07:55

    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
    }
    
    0 讨论(0)
  • 2020-12-21 08:06

    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.

    0 讨论(0)
提交回复
热议问题