2013-07-12 33 views
0

我正在使用以下代碼讀取MongoDB結果,但是while循環在無限循環中始終遍歷集合中的第一個元素,有人能指出我做錯了什麼。MongoDB Java驅動程序在讀取結果時發生無限循環

 Iterable<DBObject> list = playerData.results(); 
     if(list != null){ 
      while(list.iterator().hasNext()) { 

       DBObject obj = list.iterator().next(); 
       DBObject id = (DBObject) obj.get("_id"); 
       String player= obj.get("player").toString(); 
       //Populate the memcached here . 
       PlayerDTO rcd = new PlayerDTO(); 

       if(id != null && id.get("venue" != null && id.get("score") != null) { 

        rcd.setVenue(id.get("venue").toString()); 
        rcd.setScore(new Double(id.get("score").toString()).doubleValue()); 
       } 

      } 
     } 

回答

2

您正在將原始迭代器重新分配給while()循環的每次迭代。

Iterator i = list.iterator(); 
while(i.hasNext()) { 
    .... 
} 
+0

確實,對於(DBObject obj:list){do_stuff_with_obj}' – Gevorg

+0

更好。這是更清潔的方式。 –

+0

謝謝,但我很驚訝知道list.iterator()每次都會返回一個新的迭代器! – user1965449