Iterable和iterator, enumerations

Iterable和iterator

Iterable定义了一个接口,表示该对象是可以用来遍历的,而实现该接口的类要返回一个iterator,来具体的实现遍历.

实现了Iterable接口的类可以和foreach配合使用.如果没有应用泛型的話,iterator返回的是object,需要类型转化.

应用

1.为我们自己的class创建多个iterator

public class GameCollection  {
 private Vector<Game> games;
 private Vector<GameConsole> consoles;
 
 private class Games implements Iterable<Game> {
  @Override
  public Iterator<Game> iterator() {
   return games.iterator();
  }
 }
 
 private class Consoles implements Iterable<GameConsole> {
  @Override
  public Iterator<GameConsole> iterator() {
   return consoles.iterator();
  }
  
 }
 
 public GameCollection() {
  games = new Vector<Game>();
  consoles = new Vector<GameConsole>();
 }
 
 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<Game> {

 private Vector<Game> list;
 private int currentPosition;
 
 public CircularGamesIterator(Vector<Game> 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<Game> {
 private Vector<Game> games;
 
 public GameCollection() {
  games = new Vector<Game>();
 }
 
 public void add(Game game) {
  games.add(game);
 }

 @Override
 public Iterator<Game> iterator() {
  return new CircularGamesIterator(games);
 }
}











你可能感兴趣的:(Iterable和iterator, enumerations)