如果我迭代一个实际上是 java 中的列表的集合,这个集合会有顺序吗?

If I iterate over a collection that is actually a list in java, will the collection have order?

List<String> stringList;

//fill with strings somehow

Collection<String> stringCollection = (Collection<String>) stringList;

for(String str : stringCollection){
  //will this loop be guaranteed to iterate in the order found in stringList
}

我认为可以保证此 for-each 循环将以正确的顺序迭代,因为 syntactic sugar actually uses an iterator and the iterator() 方法在 List 中被重写以具有顺序。由于 stringCollection 的 运行 时间类型是 List,因此它将使用从列表开头开始的覆盖方法。这是正确的吗?

是的。

Collection.iteratorCollection 的 JDK 实现实现,如 ArrayList。这是面向对象编程工作方式所固有的;如果你调用一个你只知道它的接口之一的对象的方法,它仍然会调用完全实现的方法 class.

是的,增强的 for 循环将使用提供的集合的迭代器。所以如果b真的是一个列表(运行时类型),那么顺序就会得到保证。

请注意,对于新流 API (Java SE 8),这有点不同。

虽然 b.stream() 仍会保证顺序,但 b.parallelStream() 不会。

另见:https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#ordering

http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#iterator()

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

CollectionList接口都没有提供iterate()方法的实现,所以这个实现必须来自你对象的运行时间类型正在迭代。所以是的,如果您使用有序列表,集合将以可预测的顺序迭代。