有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在堆栈上实现函数isFull()的异常

import java.util.*;
import java.lang.Iterable; 

public class MyStackArray <Item> implements Iterable<Item> {
private Item I[];
        private int top;
        private int size;
        private final static int DEFAULT_SIZE = 10;

public MyStackArray () {
        this(DEFAULT_SIZE);
}

public MyStackArray (int capacity) {
        size = capacity;
        I = (Item[]) new Object [capacity];
        top = -1;
}

public Item getTop() {
        if (isEmpty())
            return null;
        return I[top];
}

public boolean isEmpty() {
        return (top == -1);
}

public boolean isFull() {
        return (top == I.length - 1);
}

public Item pop() throws EmptyStackException {
        if (isEmpty())
            throw new EmptyStackException ();
        Item item = I[top];
        I[top--] = null;
        if(top> 0 && top== I.length / 4)
            resize(I.length/2);
        return item;
}

public void push(Item item) throws FullStackException {
        if (isFull())
            throw new FullStackException ();
        if (top== I.length - 1)
            resize(2 * I.length);
        I[++top] = item;
}

public int size() {
        return (top+ 1);
}

private void resize (int newCapacity) {
        Item t[] = (Item[]) new Object[newCapacity];
        for (int i = 0; i <= top; i++)
            t[i] = I[i];
        I = t;
}

public Iterator<Item> iterator() {
        return new MyStackArrayIterator();
}

private class MyStackArrayIterator implements Iterator <Item> {
        private int i = top;

        public boolean hasNext() {
            return (i > -1);
        } 

        public Item next() {
            return I[i--];
        }

        public void remove() {
           throw new UnsupportedOperationException();
        }
    }
}

这是使用泛型方法的堆栈代码。 对我来说,一切都很顺利,唯一的例外就是工作

public boolean isFull() {
            return (top == I.length - 1);
}

我应该如何更改isFull()和push()异常才能正常工作? 在驱动程序类中,当元素的最大值为5时,我尝试推送5个元素

push("A");push("B");push("C");push("D");push("E");

size() = 5, getTop() = E

然后我再推一个元素,我的异常是堆栈已满

size() = 5, getTop() = E

所以,我把他们都干掉了

Size = 0, getTop = null

我推三个元素

push("F");push("G");push("H");

但是程序说堆栈已经满了,而最大值是5个元素。我怎样才能解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    当您弹出大多数元素时(当top== I.length / 4),您的pop方法将使堆栈的容量减半

    您的push方法应该在必要时增加容量,但isFull()阻止它这样做(因为isFull()检查(top == I.length - 1)的相同条件也用于确定何时应该增加容量)

    如果您支持增加容量,isFull()意味着什么?要么容量是固定的,在这种情况下您永远不应该更改它,要么容量不是固定的,在这种情况下isFull()应始终返回false