for-each vs for vs while [英] for-each vs for vs while

查看:66
本文介绍了for-each vs for vs while的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在ArrayList或每种List上实现"for-each"循环的最佳方法是什么.

I wonder what is the best way to implement a "for-each" loop over an ArrayList or every kind of List.

以下哪种实现是最好的,为什么?还是有最好的方法?

Which of the followings implementations is the best and why? Or is there a best way?

谢谢您的帮助.


List values = new ArrayList();

values.add("one"); values.add("two"); values.add("three"); ...

values.add("one"); values.add("two"); values.add("three"); ...

//#0
for(String value : values) { ... }

//#0
for(String value : values) { ... }

//#1
for(int i = 0; i < values.size(); i++) { String value = values.get(i); ... }

//#1
for(int i = 0; i < values.size(); i++) { String value = values.get(i); ... }

//#2
for(Iterator it = values.iterator(); it.hasNext(); ) { String value = it.next(); ... }

//#2
for(Iterator it = values.iterator(); it.hasNext(); ) { String value = it.next(); ... }

//#3
Iterator it = values.iterator(); while (it.hasNext()) { String value = (String) it.next(); ... }

//#3
Iterator it = values.iterator(); while (it.hasNext()) { String value = (String) it.next(); ... }

推荐答案

#3有一个缺点,因为迭代器it的范围超出了循环的结尾.其他解决方案没有这个问题.

#3 has a disadvantage because the scope of the iterator it extends beyond the end of the loop. The other solutions don't have this problem.

#2与#0完全相同,只是#0更具可读性且不易出错.

#2 is exactly the same as #0, except #0 is more readable and less prone to error.

#1的效率(可能)较低,因为它每次在循环中都会调用.size().

#1 is (probably) less efficient because it calls .size() every time through the loop.

#0通常是最好的,因为:

#0 is usually best because:

  • 它是最短的
  • 最不容易出错
  • 其他人一目了然,很容易理解
  • 由编译器有效地实现
  • 它不会使用不必要的名称污染您的方法范围(循环外)

这篇关于for-each vs for vs while的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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