76

Does Java's foreach loop start at the first object and in a linear fashion work it's way to the end? For example

String[] names = new String[] {"Zoe", "Bob", "Charlie", "Alex"};
for(String name : names) {
  //do stuff...
}

Is the string "Zoe" always processed first, followed by "Bob" etc? No sorting happens? I've tested it out myself and haven't found any but I need a guarantee and couldn't find anything in the docs.

10
  • 9
    short answer: yes, for arrays it does. (a bit) longer answer: depends on the object you iterate over
    – ParkerHalo
    Jan 26, 2016 at 9:45
  • @ParkerHalo how about Strings?
    – Celeritas
    Jan 26, 2016 at 9:46
  • 1
    Question: why should sorting (or any other modification) be applied by just using a loop (no matter if you use foreach or an iterator directly)?
    – Thomas
    Jan 26, 2016 at 9:47
  • 1
    @Celeritas Maybe my comment was misleading: For ALL arrays (and arraylists) the order is kept intact. For other lists/sets this might not be true!
    – ParkerHalo
    Jan 26, 2016 at 9:48
  • 1
    @ParkerHalo For other lists ... this might not be true! you're right that it might not be true but the definition of a list contains a specified/deterministic order so if it is not true for a certain list I'd not call it a list anymore. :)
    – Thomas
    Jan 26, 2016 at 10:10

2 Answers 2

70

Yes. The order is not changed. This applies to all types of collections of the Java Collection Framework implementing the iterator interface that is used by the for-loop. If you want to sort your Array, you can use Arrays.sort(names)

1
  • 7
    also note the semantics of forEach change for streams - in this case if you want to guarantee order you will want to use forEachOrdered
    – Jordan
    Jul 14, 2017 at 17:26
52

The enhanced for loop is specified in JLS 14.14.2, where its equivalent code is written.

It can be used to loop over arrays and instances of Iterable.

  • For an array, the order of iteration will be always preserved and be consistent between runs. This is because it is equivalent to a simple for loop with an index going from the beginning of the array to its end.

    The enhanced for statement is equivalent to a basic for statement of the form:

    T[] #a = Expression;
    L1: L2: ... Lm:
    for (int #i = 0; #i < #a.length; #i++) {
        {VariableModifier} TargetType Identifier = #a[#i];
        Statement
    }
    

    #a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

  • For an Iterable, it will follow the order of the corresponding Iterator (retrieved by calling Iterable.iterator()), that may or may not be consistent between runs.

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
        Statement
    }
    

    #i is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.

    You should refer to the Javadoc of each type to see if an order is consistent or not. For example, it is explicitely specified that for List, the iterator retains the order:

    Returns an iterator over the elements in this list in proper sequence.

    While it is explicitely specified that for Set, the order is unspecified (unless an extra guarantee is made):

    The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.