001package algs13; 002import stdlib.*; 003import java.util.Iterator; 004public class XFixedCapacityIterableStack<T> implements Iterable<T> { 005 T[] a; // holds the items 006 int N; // number of items in stack 007 008 @SuppressWarnings("unchecked") 009 public XFixedCapacityIterableStack (int capacity) { 010 this.a = (T[]) new Object[capacity]; // no generic array creation 011 this.N = 0; 012 } 013 public int size () { return N; } 014 public boolean isEmpty () { return (N == 0); } 015 public void push (T item) { 016 if (item == null) throw new IllegalArgumentException (); 017 a[N] = item; 018 N++; 019 } 020 public T pop () { 021 N--; 022 T result = a[N]; 023 a[N] = null; 024 return result; 025 } 026 public Iterator<T> iterator () { 027 return new ReverseArrayIterator (); 028 } 029 public class ReverseArrayIterator implements Iterator<T> { 030 private int i; 031 public ReverseArrayIterator() { 032 int numOccupied = N; 033 this.i = numOccupied - 1; 034 } 035 public boolean hasNext () { return i >= 0; } 036 public T next () { 037 T result = a[i]; 038 i--; 039 return result; 040 } 041 } 042 public static void main (String[] args) { 043 //Trace.showBuiltInObjects (true); 044 //Trace.drawStepsOfMethod ("main"); 045 //Trace.drawStepsOfMethod ("next"); 046 //Trace.drawSteps(); 047 //Trace.run (); 048 049 XFixedCapacityIterableStack<Integer> s1 = new XFixedCapacityIterableStack<> (5); 050 XFixedCapacityIterableStack<String> s2 = new XFixedCapacityIterableStack<> (3); 051 s1.push (11); 052 s1.push (21); 053 s1.push (31); 054 s2.push ("duck"); 055 s2.push ("goose"); 056 057 058 // Here's a nicer version 059 StdOut.print ("What's on the stack: "); 060 for (Integer k : s1) { 061 StdOut.print (k + " "); 062 } 063 StdOut.println (); 064 } 065}