用iterators遍历有什么好处
先看这个程序
package mycode;
import java.util.*;
class Person {
private String name;
public Person(String n) {
this.name = n;
}
public String getName() {
return this.name;
}
}
public class WhatIsIterator {
public static void main(String[] args) {
ArrayList a = new ArrayList();
Iterator it;
a.add(new Person("one"));
a.add(new Person("two"));
a.add(new Person("three"));
a.add(new Person("four"));
it = a.iterator();
/*==========================test================================*/
System.out.println("=========use for loop=====================");
for(int i = 0; i < a.size(); i++)
System.out.println(((Person)a.get(i)).getName());
System.out.println("=========use iterator======================");
while(it.hasNext())
System.out.println(((Person)it.next()).getName());
}
}
/*the output is:
=========use for loop=====================
one
two
three
four
=========use iterator======================
one
two
three
four
*/
为了问题的纯粹,写了个很简单的程序,但在实际开发中应该用FOR还是ITERATORS,哪个更好呢,为什么