IntelliJ 建议用 foreach 循环替换 while 循环。为什么?
ArrayList<Object> list = new ArrayList<Object>();
list.add(12);
list.add("Hello");
list.add(true);
list.add('c');
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next().toString());
}
当我在 IntelliJ IDEA 中输入此 Java 代码时,代码分析功能建议我将 while 循环替换为 foreach 循环,因为我正在迭代集合。这是为什么呢?
ArrayList<Object> list = new ArrayList<Object>();
list.add(12);
list.add("Hello");
list.add(true);
list.add('c');
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next().toString());
}
When I enter this Java code in IntelliJ IDEA, the code analysis feature suggests that I replace the while loop with a for each loop since I'm iterating on a collection. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是它希望您使用的内容:
自 Java 1.5 以来,这一直存在于该语言中,并且是惯用模式。仅当您需要访问迭代器的其他方法(即
remove()
)时才需要迭代器。This is what it wants you to use:
This has been in the language since Java 1.5, and is the idiomatic pattern. You need the Iterator only if you need access to the iterator's other methods (i.e.
remove()
).因为你犯错误的可能性较小,而且看起来更好; )
Because you are less likely to make mistakes and it looks better ; )
因为您有检查 Java 语言迁移辅助工具 - 'while' 循环可替换为 'for every' 活动(这是默认值),所以描述为
因此,如果您不想被告知这一点,请取消选中检查配置中的该框
because you have the inspection Java Language Migration Aids - 'while' loop replaceable with 'for each' active (which is the default), description is
so if you don't want to be told this then uncheck that box in the Inspections config
foreach 循环编写起来更短,因此更容易阅读。
The foreach loop is shorter to write and thus easier to read.
然而,与 while 循环相比,Foreach 循环创建了一个匿名类并消耗更多内存,我建议忽略该建议并使用 while 循环来更好地优化代码的使用。
The Foreach Loop however creates an anonymous class and consumes more memory compared to while loop, i would suggest to ignore the suggestion and use the while loop for better and optimized use of your code.