Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am reading MongoDB results using the following code , however the while loop runs in an infinite loop always iterating over the first element in the collection, can someone point out what I am doing wrong.

       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());
                }

            }
        }
share|improve this question

1 Answer

up vote 2 down vote accepted

You are reassigning the original iterator to the while() loop each iteration through.

Iterator i = list.iterator();
while(i.hasNext()) {
  ....
}
share|improve this answer
Or a nicer for ( DBObject obj : list ) { do_stuff_with_obj } – Gevorg 14 hours ago
indeed. that is the cleaner way. – Rick Mangi 13 hours ago
Thanks, but I am surpised to know that list.iterator() returns a new iterator everytime! – user1965449 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.