Reputation: 236
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. 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. Is this correct?
Upvotes: 3
Views: 104
Reputation: 494
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).
Upvotes: 2
Reputation: 38132
Yes, the enhanced for loop will use the iterator of the provided collection. So if b is really a list (runtime type), then the order will be guaranteed.
Note that with the new stream API (Java SE 8) this is a little bit different.
While b.stream() would still guarantee the order, b.parallelStream() wouldn't.
Also see: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#ordering
Upvotes: 2
Reputation: 405815
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. So yes, the collection will iterate in a predictable order if you use an ordered list.
Upvotes: 0
Reputation: 32323
Collection.iterator
is implemented by the JDK implementations of Collection
, like 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.
Upvotes: 1