Iterate with for loop or while loop?

后端 未结 15 1508
野趣味
野趣味 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:31

    IMHO, the for loop is less readable in this scenario, if you look at this code from the perspective of English language. I am working on a code where author does abuse for loop, and it ain't pretty. Compare following:

    for (; (currUserObjectIndex < _domainObjectReferences.Length) && (_domainObjectReferences[currUserObjectIndex].VisualIndex == index); ++currUserObjectIndex)
        ++currNumUserObjects;
    

    vs

    while (currUserObjectIndex < _domainObjectReferences.Length && _domainObjectReferences[currUserObjectIndex].VisualIndex == index)
    {
        ++currNumUserObjects;
        ++currUserObjectIndex;
    }
    

提交回复
热议问题