Iterate with for loop or while loop?

后端 未结 15 1459
野趣味
野趣味 2020-12-01 13:31

I often see code like:

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

but I write that (when Java 1.5 isn\'t available or for

15条回答
  •  不思量自难忘°
    2020-12-01 14:26

    Both are fine, but remember that sometimes access to the Iterator directly is useful (such as if you are removing elements that match a certain condition - you will get a ConcurrentModificationException if you do collection.remove(o) inside a for(T o : collection) loop).

    I prefer to write the for(blah : blah) [foreach] syntax almost all of the time because it seems more naturally readable to me. The concept of iterators in general don't really have parallels outside of programming

提交回复
热议问题