This content has been marked as final. Show 6 replies
The for each loop processes values based on what is returned by the implementation of Iterable. AbstractList implements Iterable for ArrayList, and it returns values in the order they were added. So the short answer is yes, for ArrayList, but the long answer is it depends on how Iterable is implemented for the collection you're looping on.
Implementations of List have a defined order.
Collections that don't implement List don't have a defined order.
TreeSet for example implements Set, which extends Collection but does not implement List. It will usually not return the objects in the order that they where added.
ArrayList and LinkedList both implement List, which requires that the order of objects is defined and constant. You can explicitely change that order, by removing the objects and re-inserting them at other positions.
There are also other interfaces that define other requirements on the order. For example there's SortedSet, which requires that the iterator returns the objects sorted according to their natural ordering or some provided Comparator.
never mind guys,
it is stated here that
"The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future."
so... it's pretty obvious now :-)
so... it's pretty obvious now :-)I don't see how the paragraph you quoted has anything to do with your question.
It only says that if you add objects to the List, while you're iterating over it, it will throw some Exception. That doesn't tell me anything about the order of objects being returned by that iterator.