If I iterate over a collection that is actually a list in java, will the collection have an 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 loop for each loop will iterate in the correct order, since the syntactic sugar is actually using the iterator and the iterator()

method is overridden in List

order to have an order. Since the runtime type is stringCollection

equal List

, then it will use the overridden method that starts at the beginning of the list. Is it correct?

+3


source to share


4 answers


Yes, the extended loop will use an iterator of the provided collection. So if b is indeed a list (runtime type), then the order is guaranteed.

Note that with the new Stream API (Java SE 8) this is slightly different.



While b.stream () will still guarantee ordering, b.parallelStream () will not.

Also see: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#ordering

+2


source


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



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

+2


source


Yes.

Collection.iterator

implemented by JDK implementations Collection

eg ArrayList

. This has to do with how object-oriented programming works; if you call a method of an object where you only know one of its interfaces, it will still call a method of the fully implemented class.

+1


source


Neither an interface Collection

nor List

provides an implementation for the method iterate()

, so this implementation must come from the runtime type of the object you are iterating over. So yes, the collection will iterate in a predictable order if you use an ordered list.

0


source







All Articles