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

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

Consider the following scenario.

List list = new ArrayList<>();

Now I added the String values for this li

8条回答
  •  猫巷女王i
    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
    }
    

提交回复
热议问题