For-each 与迭代器.哪个是更好的选择 [英] For-each vs Iterator. Which will be the better option

查看:20
本文介绍了For-each 与迭代器.哪个是更好的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下场景.

List<String> list = new ArrayList<>();

现在我为这个列表添加了 String 值.

Now I added the String values for this list.

我使用以下方法来处理列表中的每个元素.

I used following ways to go each and every element in the list.

选项一-使用for-each

for (String i : list) {
        System.out.println(i);
    } 

选项二-使用Iterator

Iterator it=list.iterator();
while (it.hasNext()){
   System.out.println(it.next());
}

我只想知道如果我使用 for-each 而不是 Iterator 是否有任何性能优势.而且现在在 Java 中使用 Iterator 是一种不好的做法吗?

I just want to know is there any performance advantage if I use for-each instead of Iterator. And also is it a bad practice to use Iterator now a days in Java?

推荐答案

for-each 是使用 iterators(方法 2)的语法糖.

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

如果您需要修改循环中的集合,您可能需要使用 iterators.第一种方法会抛出异常.

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
}

这篇关于For-each 与迭代器.哪个是更好的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆