I
I
Igor2018-10-25 11:48:39
Java
Igor, 2018-10-25 11:48:39

Is the "for each" loop the same as the "for" loop in Java?

We have an array of strings:

String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };

Let's try to output it like this:
for (String fruit : fruits) {
    // выводим fruit
}

So:
for (int i = 0; i < fruits.length; i++) {
    String fruit = fruits[i];
    // выводим fruit
}

The question is:
Is there a guarantee (fixed in the Java documentation or elsewhere) that the order in which the elements of an array will be output will be identical - that is, the loop for eachis guaranteed to go in order?
As far as I remember, in Python this is not necessary at all and it is not recommended to use this method, since Python can take elements in the order in which it is convenient, without giving a damn about the order.
How does this work in Java? Are there any recommendations regarding this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-10-25
@hddn

First, you don't remember well. In Python, lists are an ordered collection and, accordingly, they are iterated sequentially in order.
Secondly, the foreach loop in Java is syntactic sugar, which will be expanded into

for (Iterator i = fruits.iterator(); i.hasNext();)  {
       String fruit = i.next();
      ...
}

I
Iloveski, 2018-10-26
@Iloveski

The order of the elements during iteration is determined by the implementation contract of the collection. As for for loops, the order for the same collection in for and foreach will not differ

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question