Java堆栈类
好的,我已经编写了自己的堆栈类,而不是使用内置的堆栈类。stack类保存条目对象列表和堆栈大小(两个实例字段)。在stack类中,我有一个push方法,它将一个Entry对象添加到堆栈中。添加时,堆栈的大小应增加1 这个很好用,我已经测试过了,很好用。我可能还应该解释我的入门类包含什么。Entry类基本上有一个构造函数,它接受一个数字并保存这个数字 因此,对于Stack类,我的push方法如下所示:Java堆栈类,java,oop,stack,push,Java,Oop,Stack,Push,好的,我已经编写了自己的堆栈类,而不是使用内置的堆栈类。stack类保存条目对象列表和堆栈大小(两个实例字段)。在stack类中,我有一个push方法,它将一个Entry对象添加到堆栈中。添加时,堆栈的大小应增加1 这个很好用,我已经测试过了,很好用。我可能还应该解释我的入门类包含什么。Entry类基本上有一个构造函数,它接受一个数字并保存这个数字 因此,对于Stack类,我的push方法如下所示: public class Stack{ private List<Entry> e
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.
}
因此,它基本上与Stack类中的push方法相同,但隐藏了细节。现在这不起作用了!调用此方法时,不会向堆栈(条目列表)中添加任何内容。如果我尝试通过NumberStack推送方法推送两个数字。它应该在堆栈类中调用push方法并添加条目对象。但什么也没发生。同样,如果我直接在我的堆栈类中推送,它工作得非常好
为什么我的NumberStack课程中的push方法不起作用?它没有效果,没有任何东西被添加到堆栈中
编辑:
我试着测试它:
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方法推送后的尺寸推送=0
直接从堆栈推送后的大小=1
非常感谢您的帮助
谢谢 在NumberStack类中创建一个名为numStack.When
numStack.push(5)的堆栈对象代码>被调用,它进入NumberStack类push方法,并被推入名为numStack的堆栈对象中。因此,该对象中的实例变量大小增加。但在测试中,您正在创建另一个名为Stack的Stack类实例。但该对象中的实例变量大小仍然为0
但是在main方法中,您从堆栈实例打印大小。这就是为什么您得到答案0 首先:
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()**);
此操作失败,因为您引用了错误的实例。是否尝试调试此操作?请将您的家庭作业标记为家庭作业您缺少一个开口{推送时括号(条目)这里有你的if语句。Stack类看起来不会编译给我。你还在push方法之外向堆栈添加条目对象。你能发布一下你是如何测试这段代码的吗?因为你设置它的方式是每个NumberStack都有自己的Stack对象是的,问题已经解决了^^,但是谢谢你你的输入。顺便说一下,缺少的括号是我错误地遗漏的东西,我的代码中确实有它们
System.out.println("Size after pushing from NumStack method push = " + **numStack.size()**);