// A FigureStack is an ordered collection of figures, drawn from the bottom up. // This file contains an implementation of a FigureStack where a stack // of n figures is represented as an array of n figures ordered from // bottom (low index) to top (high index). import java.awt.*; // Allows us to use AWT classes. public class FigureStackArray extends FigureStack { //---------------------------------------------------------------------- // INSTANCE VARIABLES private Figure [] figs; // Array of figures, ordered from bottom to top. //---------------------------------------------------------------------- // CONSTRUCTOR METHOD public FigureStackArray () { figs = new Figure[0]; } //---------------------------------------------------------------------- // INSTANCE METHODS // Draws figures in this FigureStack from bottom up public void draw (Graphics g) { for (int i = 0; i < figs.length; i++) {// Must traverse bottom up! figs[i].draw(g); } } // Returns the topmost figure in this FigureStack whose bounding box // contains the point (x,y). If there is no such figure returns null. public Figure find (int x, int y) { for (int i = figs.length - 1; i >= 0; i--) {// Must traverse top down! if (figs[i].contains(x,y)) { return figs[i]; } } return null; } // Adds the given figure to the top of this FigureStack. public void add (Figure f) { Figure [] newFigs = new Figure [figs.length + 1]; for (int i = 0; i < figs.length; i++) { newFigs[i] = figs[i]; } newFigs[figs.length] = f; figs = newFigs; } // Inserts the given figure to the bottom of this FigureStack. public void insertAtBottom (Figure f) { Figure [] newFigs = new Figure [figs.length + 1]; newFigs[0] = f; for (int i = 1; i <= figs.length; i++) { newFigs[i] = figs[i-1]; } figs = newFigs; } // Removes the given figure from this FigureStack. // Assume the given figure occurs at most once in FigureStack. public void remove (Figure f) { int index = indexOf(f, figs); if (index >= 0) { // Only make smaller array if figure was found. Figure [] newFigs = new Figure [figs.length - 1]; // Copy all elements at indices less than index to newFigs. for (int i = 0; i < index; i++) { newFigs[i] = figs[i]; } // Copy all elements at indices greater than index to newFigs. for (int i = index + 1; i < figs.length; i++) { newFigs[i - 1] = figs[i]; } figs = newFigs; } } //---------------------------------------------------------------------- // CLASS METHODS // Auxiliary method that returns the index of a given figure in an array of figures. // Assume that any figure occurs at most once in the array. // It returns -1 if the figure is not found. protected static int indexOf (Figure fig, Figure [] figures) { for (int i = 0; i < figures.length; i++) { if (figures[i] == fig) { return i; } } // Only reach this point if f not in figs. return -1; } }