好的,所以我编写了自己的堆栈类,而不是使用内置的堆栈类。堆栈类包含Entry对象列表和堆栈大小(两个实例字段)。在堆栈类中,我有一个push方法,它将一个Entry对象添加到堆栈中。添加时,堆栈的大小应增加1。
这很好用我测试了它并且它有效。我可能还应该解释我的Entry类包含的内容。 Entry类基本上有一个构造函数,它接受一个数字并保存它。
因此对于Stack类,我的push方法如下所示:
public class Stack{
private List<Entry> entries = new ArrayList<Entry>();
private int size;
public void push(Entry entry)
{
if(entry == null)
String message = "The Parameter given was illegal(null)";
throw new IllegalArgumentException(message);
}
entries.add(entry) // adds the entry object to the stack (or entries List)
size ++ // increments the size by 1.
}
同样,这完全正常,我能够将Entry对象添加到我的堆栈,并且大小按照应有的增量递增。现在,我们需要创建一个名为NumberStack的新类,它基本上隐藏了详细信息,并从该类调用堆栈类中的push方法。我将向您展示我的NumberStack类如何:
public class NumberStack {
private Stack numStack = new Stack();
public void push(final float i) {
numStack.push(new Entry(i));
}
因此,基本上它与Stack类中的push方法相同,但隐藏了细节。现在这不起作用!当我调用此方法时,没有任何东西被添加到堆栈(条目列表)。如果我尝试通过我的NumberStack推送方法推送两个数字。它应该调用Stack类中的push方法并添加Entry对象。但什么都没发生。同样,如果我只是直接在我的Stack类中推送,它的工作完全正常。
为什么我的NumberStack类中的push方法不起作用?它没有任何效果,nothings被添加到堆栈中。
编辑:
我试过测试一下:
public static void main(String[] args){
System.out.println("Debugging...");
NumStack numStack = new NumStack();
Stack stack = new Stack();
System.out.println("Size before pushing from NumStack = " + stack.size());
numStack.push(5);
System.out.println("Size after pushing from NumStack method push = " + stack.size());
stack.push(new Entry(5));
System.out.println("Size after pushing directly from Stack = " + stack.size());
}
以上回复:
从NumStack推送之前的大小= 0
从NumStack方法push = 0推送后的大小
直接从Stack = 1推送后的尺寸
任何帮助非常感谢 谢谢。
答案 0 :(得分:1)
首先是:
public void push(Entry entry)
{
if(entry == null)
String message = "The Parameter given was illegal(null)";
throw new IllegalArgumentException(message);
}
entries.add(entry) // adds the entry object to the stack (or entries List)
size ++ // increments the size by 1.
}
永远不会奏效。你想要
public void push(Entry entry)
{
if(entry == null)
**{**
String message = "The Parameter given was illegal(null)";
throw new IllegalArgumentException(message);
**}**
entries.add(entry) // adds the entry object to the stack (or entries List)
size ++ // increments the size by 1.
}
打印报表也不正确:
System.out.println("Size after pushing from NumStack method push = " + stack.size());
应该是:
System.out.println("Size after pushing from NumStack method push = " + **numStack.size()**);
这是失败的,因为你引用了错误的实例。
答案 1 :(得分:0)
在NumberStack类中创建一个名为numStack的Stack对象。当调用numStack.push(5);
时,它会进入NumberStack类推送方法并被推入名为numStack的堆栈对象中。实例变量大小在该对象中递增。但是在测试中,您正在创建另一个名为stack的Stack类实例。但实例变量大小在该对象中仍为0。
但是在main方法中你可以从堆栈实例中打印大小。这就是你得到答案0的原因。