我想在我的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?

最佳答案

Iterable接口通常由某种集合来实现。在您的情况下,Prison类而不是可以声明为实现PrisonCellIterable<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接口方法的类。 (这通常由collection类的私有内部类完成,因为迭代器通常会访问collection的内部数据结构-不应在公共api中公开的东西。)它可能会为方法,因为对象数组支持的集合通常不支持该操作。 (由remove()构造的Iterator返回的List以这种方式运行。)

这是对此类内部类的快速尝试。我是在Arrays.asList()数组的第一个numPrisonCells元素有效的前提下编写的:

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();
        }
    }
}


注意,这不是一个非常健壮的迭代器实现。特别是,如果在迭代过程中修改了prisonCells数组,它可能会跳过或重复元素。 Java Collections Framework通过让每个集合对象维护一个内部prisonCells修改计数来解决此问题,并且在构造每个迭代器时,它将初始化自己的修改计数副本。然后,在对迭代器进行的每个方法调用中,它都会检查集合的mod计数是否与其内部副本匹配,如果不匹配,则抛出long

*当然,您可能想让ConcurrentModificationException实现PrisonCell。 :)

10-04 17:51