Java 集合 之 Iterator 迭代器
http://www.verejava.com/?id=17159874583439
/**
* 打印输出 地铁的所有站点信息
Iterator iterator();
Boolean hasNext();
Object next();
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List stationList=new ArrayList();
//添加站点信息
stationList.add(new Station("北京大学"));
stationList.add(new Station("中关村"));
stationList.add(new Station("海淀黄庄"));
stationList.add(new Station("人民大学"));
//索引方式输出
for(int i=0;i<stationList.size();i++)
{
Station station=(Station)stationList.get(i);
System.out.print(station.getName()+" -> ");
}
System.out.println("");
//以数组方式输出
Object[] stations=stationList.toArray();
for(int i=0;i<stations.length;i++)
{
Station station=(Station)stations[i];
System.out.print(station.getName()+" -> ");
}
//以迭代器的方式输出
System.out.println("");
Iterator iter=stationList.iterator();
while(iter.hasNext())//是否存在下一个元素
{
//获得下一个元素
Station station=(Station)iter.next();
System.out.print(station.getName()+" -> ");
}
}
}
//地铁站点类
public class Station {
private String name;
public Station(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}