• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is for each guaranteed to retain order?  RSS feed

 
Brian Tkatch
Bartender
Posts: 598
26
Linux Notepad Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is for each guaranteed to retain order?
That is, will the above program always print "12" and not "21"?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

The for/each will always iterate using the natural order for the collection over which it iterates. For an array, as in your example, that would be in index order. For other collection types, a HashMap for example, the natural order may be different (or even unspecified).
 
Tim Cooke
Marshal
Posts: 4044
239
Clojure IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For your specific example using an array the answer is yes, predictable order will be observed.

However, in general terms the answer is it depends.

It depends on the Collection type, or more specifically the Iterable type. For example, iterating over an ArrayList will give you a predictable order, but iterating over a HashSet makes no guarantees of order.
 
Brian Tkatch
Bartender
Posts: 598
26
Linux Notepad Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Cooke wrote:For your specific example using an array the answer is yes, predictable order will be observed.

However, in general terms the answer is it depends.

It depends on the Collection type, or more specifically the Iterable type. For example, iterating over an ArrayList will give you a predictable order, but iterating over a HashSet makes no guarantees of order.


Wow, never thought it would be the Iterator and not the loop itself.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can read about the for‑each loop in the Java® Language Specification, though we all know that can be hard to understand.
In the case of arrays the for‑each loop behaves as if it were syntactic sugar forIn the case of Collections the for‑each loop behaves as if it were syntactic sugar forThat assumes the array is T[] and the collection is a Collection<T>.

You cannot iterate a Map but you can get Sets from it which you can iterate, using these three methods: 1 2 3.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!