重新初始化ArrayList的迭代器不起作用

时间:2012-02-04 06:25:16

标签: java arraylist iterator

鉴于以下内容:

    // get the list of the players , in order to start the game 
    ArrayList<String> players = this.m_maze.getPlayers();
    // human side 
    String humanPlayer = iterator.next();
    String computerPlayer = null;
    // define iterator for the players 

    Iterator<String> iterator = players.iterator();     
    boolean humanSide = true ,computerSide = false;    // assume the human player is starting the game 


    // controller - start a game between the players , at least two players are playing 

    while (this.m_rounds > 0)  
    {

        if (humanSide == false && computerSide == true) // then this is the turn of the human side 
        {
            if (iterator.hasNext() == false)
            {
                // reinitialize the iterator
                Iterator<String> iterator = players.iterator();

            }
            while (iterator.hasNext())


                        // more code 

我尝试重用迭代器,但是我得到了一个“Duplicate local variable iterator”编译错误。我该如何重用该迭代器? 谢谢,罗恩

编辑:

            if (iterator.hasNext() == false)
            {
                // reinitialize the iterator
                iterator = players.iterator();

            }
            while (iterator.hasNext())
            {
                computerPlayer = iterator.next();

                // computer decides what would be his next move , between 1 - 3 

5 个答案:

答案 0 :(得分:3)

不要重新声明变量;只是分配它。

if (iterator.hasNext() == false) {
    iterator = players.iterator();
}

您应该注意嵌套循环行为。你真的有意拥有以下块吗

while (iterator.hasNext()) { ... }

实际检查这个条件?

while (iterator.hasNext() && (this.m_rounds > 0)) { ... }

答案 1 :(得分:1)

您已将Iterator<String> iterator = players.iterator();放入循环中。

因此每次尝试创建名为iterator的变量时。

把它的声明放在循环之外......比如

 Iterator<String> iterator;     //here ****
 while (this.m_rounds > 0)  
   {

    if (humanSide == false && computerSide == true) // then this is the turn of the human side 
    {
        if (iterator.hasNext() == false)
        {
            // reinitialize the iterator
            iterator = players.iterator();

        }
        while (iterator.hasNext())

答案 2 :(得分:1)

我认为google guava与Iterators#cycle几乎有你想要的东西。

像这样使用:

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

......你永远不会耗尽玩家。

答案 3 :(得分:1)

不要使用这样的迭代器,它可以搞砸了,只是按照旧的方式去做,我的意思是使用着名的Iterator先生“我”。此外,代码看起来更合理。

    while(m_rounds > 0){

        if(i == players.size()) {
            i = 0;
        }

        currentPlayer = players.get(i);

        //Do what you want to do with the current player...

        ...

        //Next
        i++;


    }

一个小小的建议,你真的需要两个标志,我的意思是人类的侧面和计算机侧面?不会只使用一个就足够了吗?你的if-else块会看起来更简单明了:

if(humanSide) {

   //Hope this move wouldn't crush your logic.

} else {

  //Algorithm based awesome move.

}

答案 4 :(得分:0)

好的,只需删除Iterator<String>,意思是,当重用迭代器时只需写:iterator = players.iterator();

谢谢大家!!