[英]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
}
I think it is guaranteed that this for-each loop will iterate in the correct order, since the syntactic sugar actually uses an iterator and the iterator()
method is overridden in List
to have an order. 我认为保证这个for-each循环将以正确的顺序迭代,因为语法糖实际上使用了迭代器,并且在List
重写了iterator()
方法以获得顺序。 Since the run time type of stringCollection
is a List
, then it will use the overridden method which starts at the beginning of the list. 由于stringCollection
的运行时类型是List
,因此它将使用从列表开头开始的重写方法。 Is this correct? 它是否正确?
Yes, the enhanced for loop will use the iterator of the provided collection. 是的,增强的for循环将使用提供的集合的迭代器。 So if b is really a list (runtime type), then the order will be guaranteed. 因此,如果b实际上是一个列表(运行时类型),那么订单将得到保证。
Note that with the new stream API (Java SE 8) this is a little bit different. 请注意,使用新的流API(Java SE 8),这有点不同。
While b.stream() would still guarantee the order, b.parallelStream() wouldn't. 虽然b.stream()仍然保证订单,但b.parallelStream()不会。
Also see: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#ordering 另见: https : //docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#ordering
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#iterator() 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 ). 无法保证返回元素的顺序( 除非此集合是某个提供保证的类的实例 )。
Collection.iterator
is implemented by the JDK implementations of Collection
, like ArrayList
. Collection.iterator
通过的JDK实现来实现Collection
,像ArrayList
。 This is inherent to how object oriented programming works; 这是面向对象编程如何工作所固有的; if you call a method of an object where you only know one of it's interfaces, it will still call the method of the fully implemented class. 如果你调用一个只知道其中一个接口的对象的方法,它仍然会调用完全实现的类的方法。
Neither the Collection
nor List
interface provide an implementation for the iterate()
method, so this implementation must come from the run-time type of the object you're iterating over. Collection
和List
接口都没有为iterate()
方法提供实现,因此该实现必须来自您正在迭代的对象的运行时类型。 So yes, the collection will iterate in a predictable order if you use an ordered list. 所以是的,如果您使用有序列表,集合将以可预测的顺序迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.