Difference between moving an Iterator forward with a for statement and a while statement

前端 未结 5 2101
别跟我提以往
别跟我提以往 2021-01-11 10:16

When I use an Iterator of Object I use a while loop (as written in every book learning Java, as Thinking in Java of Bruce Eckel):

I         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-11 10:38

    The purpose of declaring the Iterator within the for loop is to minimize the scope of your variables, which is a good practice.

    When you declare the Iterator outside of the loop, then the reference is still valid / alive after the loop completes. 99.99% of the time, you don't need to continue to use the Iterator once the loop completes, so such a style can lead to bugs like this:

    //iterate over first collection
    Iterator it1 = collection1.iterator();
    while(it1.hasNext()) {
       //blah blah
    }
    
    //iterate over second collection
    Iterator it2 = collection2.iterator();
    while(it1.hasNext()) {
       //oops copy and paste error! it1 has no more elements at this point
    }
    

提交回复
热议问题