Converting loops (Java Beginner question)

前端 未结 5 433
独厮守ぢ
独厮守ぢ 2020-12-20 06:45

Does Converting between loops always works like this? or there is some situation that it does not? and what is the fastest way to check while I\'m solving a question like th

5条回答
  •  太阳男子
    2020-12-20 07:12

    The other members have covered the execution semantics. But I wanted to add the variable scoping semantics.

    In Java, you can do this:

    for (Iterator i = localList.iterator(); i.hasNext(); ) {
      String element = i.next();
      if (...) {
        i.remove();
      }
    }
    
    for (Iterator i = importList.iterator(); i.hasNext(); ) {
      String element = i.next();
      if (...) {
        i.remove();
      }
    }
    

    Where the variable 'i' is used twice.

    In order to translate that to while loops with correct scoping, you need to use additional code blocks:

    {
      Iterator i = localList.iterator();
      while (i.hasNext()) {
        String element = i.next();
        if (...) {
          i.remove();
        }
      }
    }
    
    {
      Iterator i = importList.iterator();
      while (i.hasNext()) {
        String element = i.next();
        if (...) {
          i.remove();
        }
      }
    }
    

    Note how the additional { ... } allows you to use the same variable names.

    While not as important in Java, in languages like C++, the scoping has important ramifications beyond just being able to use the same variable names. Object destruction, IIA (instantiation is acquisition) etc are affected by the additional block.

提交回复
热议问题