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

后端 未结 8 1328
悲&欢浪女
悲&欢浪女 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: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 iter = stringList.iterator(); iter.hasNext(); ) {
      String s = iter.next();
      ...
    }
    

提交回复
热议问题