lazarusL
lazarusL

Reputation: 236

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

Answers (4)

Marek-A-
Marek-A-

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

Puce
Puce

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

Bill the Lizard
Bill the Lizard

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

durron597
durron597

Reputation: 32323

Yes.

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

Related Questions