foreach loop a java creation?

前端 未结 5 2063
粉色の甜心
粉色の甜心 2020-12-21 18:34

Why was this loop introduced in java?Is it a java creation? What is its purpose(increases memory/cpu utilisation efficiency)?

5条回答
  •  离开以前
    2020-12-21 19:09

    Why was this loop introduced in java?

    It's just to ease looping over generic collections and arrays. Instead of

    for (int i = 0; i < strings.length; i++) {
        String string = strings[i];
        // ...
    }
    

    you can just do

    for (String string : strings) {
        // ...
    }
    

    which makes the code more readable and better maintainable.

    Is it a java creation?

    No, it existed in other languages long before Java. Java was relatively late in implementing it.

    What is its purpose?

    See the first answer.

    To learn more about it, checkout the Sun guide on the subject.

    Update: this does not mean that it makes the other kinds of loops superfluous. the for loop using index is still useful if you'd like to maintain a loop counter for other purposes than getting the item by index. The for loop using an iterator is still useful if you'd like to remove or change elements of the collection itself inside a loop.

提交回复
热议问题