Question: NEED HELP GETTING PUSH METHOD TO WORK SO THAT WHEN PUSHING ONTO A FULL LEAKYSTACK IT LEAKS THE OLDEST ELEMENT THEN ADDS THE NEW ONE

NEED HELP GETTING PUSH METHOD TO WORK SO THAT WHEN PUSHING ONTO A FULL LEAKYSTACK IT "LEAKS" THE OLDEST ELEMENT THEN ADDS THE NEW ONE ON TOP! ---Not sure what i am doing wrong---

Assignment:

LeakyStack ADT:

The introduction of Section 6.1 notes that stacks are often used to provide undo support in applications like a Web browser or text editor. While support for undo can be implemented with an unbounded stack, many applications provide only limited support for such an undo history, with a fixed stack capacity.

When a push is invoked on a LeakyStack at full capacity, rather than throwing an exception, accept the pushed element at the top while leaking the oldest element from the bottom of the stack to make room.

Write the generic interface for this LeakyStack ADT. Include a toString and equals method in the interface.

Give an efficient static implementation of the LeakyStack abstraction.

What i have:

////////////////// LeakyStack/////////////////

public class LeakyStack implements Stack { public static final int CAPACITY = 1000; //defult array capacity private E[] data; //generic array used for storage private int t = -1; //index of top element in stack

/** * */ public LeakyStack() { //construc stack with default capacity this(CAPACITY); }

/** * * @param capacity */ public LeakyStack(int capacity) { //construct stack with given capacity data = (E[]) new Object[capacity]; //safe cast, compiler may give warning }

@Override public int size() { return (t + 1); }

@Override public boolean isEmpty() { return (t == -1); }

@Override public void push(E e) {

if (data.length >= size()) { for (int j = 0; j < size() - 1; j++) { data[j] = data[j + 1]; } data[size()] = e; } // else if(data.length < size()) data[++t] = e; }

@Override public E top() { if (isEmpty()) { return null; } return data[t]; }

@Override public E pop() { if (isEmpty()) { return null; } E answer = data[t]; data[t] = null; //dereference to help garbage collection t--; return answer; } public String toString() { String result = "";

for (int scan = 0; scan <= t; scan++) result = result + data[scan].toString()+ " ";

return result; } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!