java 在java中哪个循环最好迭代一个集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37078661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:10:37  来源:igfitidea点击:

In java which loop is best to iterate over a collection

javaloopscollections

提问by DJG

What criteria should be met when deciding which of the following loops to use to iterate over elements in a collection. For example in what context will one loop be more efficient than another?

在决定使用以下哪个循环来迭代集合中的元素时,应满足哪些条件。例如,在什么情况下一个循环会比另一个更有效?

  • For Loop ??
  • While Loop ??
  • For-Each Loop ??
  • 循环??
  • 虽然循环 ??
  • For-Each 循环 ??

回答by njzk2

There are 3 types of loops in Java. They do different things, and with regards to Collections, have different usage.

Java 中有 3 种类型的循环。他们做不同的事情,对于Collections,有不同的用法。

Traditional For loop

传统的 For 循环

The traditional for loop looks like:

传统的 for 循环如下所示:

for (int i = 0; i < list.length(); i++) {
    Object o = list.get(i);
}

It is useful when you need to use the index for something else than accessing the element, like when you have 2 loops, or when you affect the index to some value in the object.

当您需要将索引用于访问元素之外的其他用途时,例如当您有 2 个循环时,或者当您将索引影响到对象中的某个值时,它很有用。

It can be used only with lists, and even then, should never be used with LinkedLists, because get(i)is O(n)in those. It cannot be used with other Collections such as Sets.

它只能使用列表中使用,即使如此,不应该与使用LinkedListS,因为get(i)O(n)在那些。它不能与其他Collections一起使用,例如Sets。

The same syntax can also be used on arrays (use lengthfield instead of the length()method), or on Strings (using size()and charAt)

相同的语法也可用于数组(使用length字段而不是length()方法)或字符串(使用size()and charAt

It is usually not the best loop. It does not prevent you from messing with the ivariable, or with the content of the list, which can lead to surprising results.

它通常不是最好的循环。它不会阻止您弄乱i变量或 的内容list,这可能会导致令人惊讶的结果。

While loop

While 循环

While loop can be used for a lot of things, but in the case of a Collection, it is used when you need to remove elements from a list. It requires an Iterator, which is a little more work:

While 循环可用于很多事情,但在 a 的情况下,Collection当您需要从列表中删除元素时使用它。它需要一个Iterator,这是一个多一点的工作:

Iterator<String> iter = coll.iterator();
while (iter.hasNext()) {
    String elem = iter.next();
    iter.remove();
}

It allows you to safely delete any element of the collection. It works on any Collection(Listor Set).

它允许您安全地删除集合中的任何元素。它适用于任何CollectionListSet)。

It does not give you direct access to the index, but Collectionand Iterableknow nothing about indexed access anyway.

它不会给你指数的直接访问,但CollectionIterable一无所知索引访问反正。

Fast-enum for loop

快速枚举 for 循环

The latest addition is a short version of the above, without the possibility of removing items:

最新添加的是上述内容的简短版本,没有删除项目的可能性:

for (String elem : coll) {

}

It is the clearest. It does not involve any extra variable and works on any Iterable, as well as on arrays.

这是最清楚的。它不涉及任何额外的变量,适用于 anyIterable以及数组。

You are forbidden from modifying the collection(it will throw a ConcurrentModificationException) when looping (from inside the loop or from another thread), which guarantees the consistency of the data.

禁止ConcurrentModificationException在循环时(从循环内部或从另一个线程)修改集合(它会抛出),这保证了数据的一致性。

Use it whenever possible.

尽可能使用它。

回答by Vikrant Kashyap

Best Way is Class Iteratoruse to Iterate througout the Collectionbut you have not mentioned Iterator

最好的方法是Iterator使用类来迭代整个Collection但你没有提到Iterator

  1. I will recommend foreachloop. because in foror whileor do-whilethere is need of defining external Counters to get end of the loop condition. but in for-eachthere is no need of external Variables.

  2. IndexOutOfBoundException:- It will not raise in for-eachbut if we type any logical mistake then other may raise this exception (in context of Array).

  1. 我会推荐foreach循环。因为 inforwhileordo-while需要定义外部计数器来获得循环结束条件。但for-each不需要外部变量。

  2. IndexOutOfBoundException:- 它不会引发,for-each但如果我们输入任何逻辑错误,那么其他人可能会引发此异常(在 Array 的上下文中)。

but if your need to play with the indexthen you should use foror do-while()or while().

但如果你需要与打index那么你应该使用fordo-while()while()

回答by Bernd Elkemann

First use a for-each loop when it is appropriate: iterating over the whole collection and only needing the elements (not their index).

在适当的时候首先使用 for-each 循环:迭代整个集合并且只需要元素(而不是它们的索引)。

If for-each is not appropriate then choose for-vs.-while based on whether you reasonably need the 3 parts of a for-loop, ie. use while if you would only use the condition/middle part of a for-loop.

如果 for-each 不合适,则根据您是否合理需要 for 循环的 3 个部分,即选择 for-vs.-while。如果您只想使用 for 循环的条件/中间部分,请使用 while。

回答by PeaceIsPearl

If the collection is arraylist here are the three choices available :

如果集合是 arraylist,这里有三个可用的选择:

array index loop:

数组索引循环:

for (int i = 0; i < collection.length; i++) {
        type array_element = collection.get(index);

    }

the Iterator hasNext()/next():

迭代器 hasNext()/next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
    type type = (type) iterator.next();

}

simplest :

最简单的:

for (iterable_type iterable_element : collection) {

}

The first one is useful when you need the index of the element as well.

当您还需要元素的索引时,第一个很有用。

The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate.

当您不需要元素的索引但可能需要在迭代时删除元素时,第二个很有用。

The third version is simple and preferred by all. It is short and works for all cases where you do not need any indexes or the underlying iterator.

第三个版本很简单,大家都喜欢。它很短,适用于不需要任何索引或底层迭代器的所有情况。