I want to make an iterator() method in my Prison class but to do that, I want to make a new class that will contain the boolean hasNext() and PrisonCell next() methods of an iterator that will implement a certain interface.
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?