如何在Java中使用Iterator / Iterable?

时间:2014-09-23 04:20:02

标签: java iterator iterable

我想在iterator()课程中制作Prison方法,但为了做到这一点,我想制作一个包含boolean hasNext()PrisonCell next()方法的新课程一个将实现某个接口的迭代器。

package iterator;
import java.util.Iterator;
public class Driver {

  public static void main(String args[]) {
    Prison prison= new Prison(5);
    Iterator<PrisonCell> iter;

    prison.addCell(new PrisonCell("A", 3));
    prison.addCell(new PrisonCell("B", 9));
    prison.addCell(new PrisonCell("C", 6));

    iter= prison.iterator(); //I want to make the iterator() method in my Prison class

    while (iter.hasNext())
      System.out.println(iter.next());
  }
    /**output here would be:
    Name: A, numPrisoners: 3
    Name: B, numPrisoners: 9
    Name: C, numPrisoners: 6
    **/

}



package iterator;
public class PrisonCell { //how would I implement the Iterable<> iterface here?

  private String name;
  private int numPrisoners;

  public PrisonCell(String name, int numPrisoners) {
    this.name= name;
    this.numPrisoners= numPrisoners;
  }

  public String toString() {
    return "Name: " + name + ", numPrisoners: " + numPrisoners;
  }

}



package iterator;
public class Prison{

    PrisonCell prisonCells[];
    int numPrisonCells;

    public Prison(int size) {
        prisonCells= new PrisonCell[size];
        numPrisoners= 0;
    }

    // just do nothing if the array is full
    public void addCell(PrisonCell newPrisonCell) {
        if (numPrisonCells < prisonCells.length)
            prisonCells[numPrisonCells++]= newPrisonCell;
    }

    //how do I write iterator() method here??
}

package iterator;
public class Iterator<PrisonCell>//is it supposed to implement an interface here?
//which fields here?
public Iterator() //constructor here
//I think boolean hasNext() and PrisonCell next() methods go here?

1 个答案:

答案 0 :(得分:2)

Iterable接口通常由某种集合实现。在您的情况下,它是Prison类,而不是PrisonCell可以声明实现Iterable<PrisonCell> * 它需要实现一个方法: iterator(),会返回Iterator<PrisonCell>

返回什么对象?一种简单的方法是简单地将数组包装在List中,并让List返回Iterator

public class Prison implements Iterable<PrisonCell> {
    PrisonCell prisonCells[];

    . . .

    public Iterator<PrisonCell> iterator() {
        return Arrays.asList(prisonCells).iterator();
    }
}

(您可以考虑将prisonCellsPrisonCell[]更改为List<PrisonCell>;我建议您这样做。然后您可以直接要求它返回Iterator。)

或者,编写自己的类来实现Iterator接口方法。 (这通常由集合类的私有内部类完成,因为迭代器通常访问集合的内部数据结构 - 不应该在公共API中公开。)它应该为{{{{{ 1}}方法,因为对象数组支持的集合通常不支持该操作。 (由remove()构建的Iterator返回的List以这种方式行事。)

这是对这样一个内部阶级的快速尝试。我是在Arrays.asList()数组的唯一numPrisonCells元素唯一有效的假设下写的:

prisonCells

请注意,这不是一个非常强大的迭代器实现;特别是,如果在迭代期间修改了public class Prison implements Iterable<PrisonCell> { PrisonCell prisonCells[]; int numPrisonCells; . . . public Iterator<PrisonCell> iterator() { return new PrisonIterator(); } private class PrisonIterator implements Iterator<PrisonCell> { private int index; PrisonIterator() { index = -1; } public boolean hasNext() { return index < numPrisonCells - 1; } public PrisonCell next() { if (index < numPrisonCells - 1) { return prisonCells[++index]; } else { throw new NoSuchElementException(); } } public void remove() { // you could actually implement something here throw new UnsupportedOperationException(); } } } 数组,它可以跳过或重复元素。 Java Collections Framework通过让每个集合对象保持内部prisonCells修改计数来解决这个问题,并且在构造每个迭代器时,它会初始化它自己的修改计数副本。然后在每个方法调用迭代器时,它会检查集合的mod计数是否与其内部副本匹配,如果不匹配,则抛出long

* 当然,您可能希望ConcurrentModificationException实施PrisonCell。 :)

相关问题