【发布时间】:2015-08-24 06:57:19
【问题描述】:
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();
}
}
}
这是 Stack 使用泛型方法的代码。 对于 isEmpty 来说,一切都很顺利,那个例外就是工作。
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
我推送 3 个元素,
push("F");push("G");push("H");
但是程序说堆栈已经满了,而最大值是 5 个元素。我该如何解决?
【问题讨论】:
-
在
push()中,如果堆栈已满,您将抛出异常,同时尝试调整它的大小。这怎么可能。当您抛出异常时,程序控件将直接跳转到最近的匹配异常处理程序。所以,恕我直言,堆栈不会调整大小。 -
看看 StringBuilder.append 它可能会帮助您了解如何使用堆栈/数组 (grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/…)
-
@skrtbhtngr 好的,我尝试删除 resize() 方法并将 pop() 和 push() 修改为固定容量堆栈。它有效。感谢您的建议。