foreach循环创建Java吗? [英] foreach loop a java creation?

查看:67
本文介绍了foreach循环创建Java吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Java中引入了这个循环?它是Java的创造吗?它的目的是什么(提高内存/cpu的使用效率)?

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

推荐答案

为什么在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];
    // ...
}

你可以做

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

这使代码更具可读性和更好的可维护性.

which makes the code more readable and better maintainable.

这是Java创作吗?

不,它早在Java之前就已存在其他语言.Java实施起来相对较晚.

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

它的目的是什么?

查看第一个答案.

要了解更多信息,请查看 Sun指南.

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

更新:这并不意味着它会使其他类型的循环变得多余.如果您要维护循环计数器以用于除通过索引获取项以外的其他目的,则使用索引的for循环仍然有用.如果您想在循环内删除或更改集合本身的元素,则使用迭代器的for循环仍然有用.

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.

这篇关于foreach循环创建Java吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆