【发布时间】:2011-07-27 03:35:15
【问题描述】:
可能的重复:
What are the Advantages of Enhanced for loop and Iterator in Java ?
Is there a performance difference between a for loop and a for-each loop?
下面的代码展示了使用for循环和迭代器我们可以迭代集合的元素那么for循环和迭代器有什么区别以及为什么我们应该在集合的情况下只使用迭代器
ArrayList<String> list=new ArrayList<String>();
list.add("dipu");
list.add("alok");
list.add("alok");
list.add("jyoti");
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(1);
al.add(2);
String a[]={"a","b"};
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));;
}
for(Integer t:al)
{
System.out.println(t);
}
for (Iterator iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
Iterator it=list.iterator();
while(it.hasNext())
{
String st=it.next().toString();
System.out.println(st);
}
【问题讨论】:
-
增强的 for 循环在正常访问元素时比普通 for 循环快一点,但不适用于基于数组的集合,因为它们可以轻松地立即访问索引