Iterable和iterator
Iterable定义了一个接口,表示该对象是可以用来遍历的,而实现该接口的类要返回一个iterator,来具体的实现遍历.
实现了Iterable接口的类可以和foreach配合使用.如果没有应用泛型的話,iterator返回的是object,需要类型转化.
应用
1.为我们自己的class创建多个iterator
public class GameCollection { private Vectorgames; private Vector consoles; private class Games implements Iterable { @Override public Iterator iterator() { return games.iterator(); } } private class Consoles implements Iterable { @Override public Iterator iterator() { return consoles.iterator(); } } public GameCollection() { games = new Vector (); consoles = new Vector (); } public void add(Game game) { games.add(game); } public void add(GameConsole console) { consoles.add(console); } public Games games() { return new Games(); } public Consoles consoles() { return new Consoles(); }}
GameCollection gc = new GameCollection();//Add games and consoles with gc.add()for (Game g : gc.games()) { System.out.println(g.getName());}for (GameConsole g : gc.consoles()) { System.out.println(g.getName());}
2.创建自己的iterator
public class CircularGamesIterator implements Iterator{ private Vector list; private int currentPosition; public CircularGamesIterator(Vector games) { list = games; currentPosition = 0; } @Override public boolean hasNext() { return currentPosition < list.size(); } @Override public Game next() { Game el = list.elementAt(currentPosition); currentPosition = (currentPosition + 1) % list.size(); return el; } @Override public void remove() { }}
public class GameCollection implements Iterable{ private Vector games; public GameCollection() { games = new Vector (); } public void add(Game game) { games.add(game); } @Override public Iterator iterator() { return new CircularGamesIterator(games); }}