Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 {
- 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??
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement