For-each vs Iterator. Which will be the better option

后端 未结 8 1304
悲&欢浪女
悲&欢浪女 2020-12-02 09:14

Consider the following scenario.

List list = new ArrayList<>();

Now I added the String values for this li

相关标签:
8条回答
  • 2020-12-02 09:36

    for-each is syntactic sugar for using iterators (approach 2).

    You might need to use iterators if you need to modify collection in your loop. First approach will throw exception.

    for (String i : list) {
        System.out.println(i);
        list.remove(i); // throws exception
    } 
    
    Iterator it=list.iterator();
    while (it.hasNext()){
        System.out.println(it.next());
        it.remove(); // valid here
    }
    
    0 讨论(0)
  • 2020-12-02 09:36

    foreach uses iterators under the hood anyway. It really is just syntactic sugar.

    Consider the following program:

    import java.util.List;
    import java.util.ArrayList;
    
    public class Whatever {
        private final List<Integer> list = new ArrayList<>();
        public void main() {
            for(Integer i : list) {
            }
        }
    }
    

    Let's compile it with javac Whatever.java,
    And read the disassembled bytecode of main(), using javap -c Whatever:

    public void main();
      Code:
         0: aload_0
         1: getfield      #4                  // Field list:Ljava/util/List;
         4: invokeinterface #5,  1            // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
         9: astore_1
        10: aload_1
        11: invokeinterface #6,  1            // InterfaceMethod java/util/Iterator.hasNext:()Z
        16: ifeq          32
        19: aload_1
        20: invokeinterface #7,  1            // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
        25: checkcast     #8                  // class java/lang/Integer
        28: astore_2
        29: goto          10
        32: return
    

    We can see that foreach compiles down to a program which:

    • Creates iterator using List.iterator()
    • If Iterator.hasNext(): invokes Iterator.next() and continues loop

    As for "why doesn't this useless loop get optimized out of the compiled code? we can see that it doesn't do anything with the list item": well, it's possible for you to code your iterable such that .iterator() has side-effects, or so that .hasNext() has side-effects or meaningful consequences.

    You could easily imagine that an iterable representing a scrollable query from a database might do something dramatic on .hasNext() (like contacting the database, or closing a cursor because you've reached the end of the result set).

    So, even though we can prove that nothing happens in the loop body… it is more expensive (intractable?) to prove that nothing meaningful/consequential happens when we iterate. The compiler has to leave this empty loop body in the program.

    The best we could hope for would be a compiler warning. It's interesting that javac -Xlint:all Whatever.java does not warn us about this empty loop body. IntelliJ IDEA does though. Admittedly I have configured IntelliJ to use Eclipse Compiler, but that may not be the reason why.

    0 讨论(0)
  • 2020-12-02 09:38

    The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays.

    Don't worry about performance differences. Such micro-optimization is an irrelevant distraction. If you need to remove items as you go, use an Iterator. Otherwise for loops tend to be used more just because they're more readable ie:

    for (String s : stringList) { ... }
    

    vs:

    for (Iterator<String> iter = stringList.iterator(); iter.hasNext(); ) {
      String s = iter.next();
      ...
    }
    
    0 讨论(0)
  • 2020-12-02 09:42

    for-each is an advanced looping construct. Internally it creates an Iterator and iterates over the Collection. Only possible advantage of using an actual Iterator object over the for-each construct is that you can modify your collection using Iterator's methods like .remove(). Modifying the collection without using Iterator's methods while iterating will produce a ConcurrentModificationException.

    0 讨论(0)
  • 2020-12-02 09:47

    Best way to do this is in java 8 is,

    list.forEach(System.out::println);
    

    Here are some useful links.

    1. Java 8 Iterable.forEach() vs foreach loop

    2. http://www.javaworld.com/article/2461744/java-language/java-language-iterating-over-collections-in-java-8.html

    3. https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html

    0 讨论(0)
  • 2020-12-02 09:49

    If you want to replace items in your List, I would go old school with a for loop

    for (int nIndex=0; nIndex < list.size(); nIndex++) {
      Obj obj = (Obj) list.get(nIndex);
    
      // update list item
      list.set(nIndex, obj2);
    }
    
    0 讨论(0)
提交回复
热议问题