先看这个程序
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,哪个更好呢,为什么
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,哪个更好呢,为什么
Iterator隐藏了容器底层的结构.
迭代器是一个对象,它的工作是遍历并选择序列中的对象,而客户端程序员不必知道或关心该序列底层的结构.而且创建它的代价小.
import java.util.*;
public class Printer{
static void printAll(Iterator e){
while(e.hasNext())
System.out.println(e.next());
}
}
这个程序中,没有关于序列类型的信息,只有一个迭代器Iterator.不需要知道要遍历的是ArrayList还是LinkedList.
里面有个迭代子模式
当然如果你系统要优化的化,而且你能肯定ArrayList有多少个对象的话,用for速度可以快些,嘎嘎