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

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

问题描述

考虑下面的情况。

 列表< String> list = new ArrayList<>(); 

现在我为此添加了字符串值名单。



我使用以下方法去列表中的每一个元素。



选项一使用

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





选项二 - 使用 Iterator

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





$ b我只是想知道如果使用 for-each 而不是 Iterator 。在Java中使用迭代器现在是不好的习惯吗?

是使用迭代器(方法2)的语法糖。

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



$ p $ for(String i:list){
System.out.println(i) ;
list.remove(i); //抛出异常
}

Iterator it = list.iterator(); (it.hasNext()){
System.out.println(it.next());
it.remove(); //在此处有效
}


Consider the following scenario.

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

Now I added the String values for this list.

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

Option one- use for-each

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

Option two- use Iterator

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

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 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
}

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

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