在Java中为我自己的LinkedList类编写自己的peek()方法
问题描述:
因此我被要求为Java中的链接列表编写peek()
方法。唯一的情况是我想要“偷看”的对象是一个基类型的私有变量,它存在于我的LinkedList类的私有类中。我想用我的peek()
方法返回对象并打印出来。我知道这与访问一个私有变量有关,但我无法使它与我所拥有的一致。这里是我的代码片段:在Java中为我自己的LinkedList类编写自己的peek()方法
class LinkedStack <Base>
{
private class Run
{
private Base object;
private Run next;
private Run (Base object, Run next)
{
this.object = object;
this.next = next;
}
}
...
public Base peek()
{
if(isEmpty())
{
throw new IllegalStateException("List is empty");
}
return object; //this throws an error
}
...
public void push(Base object)
{
top = new Run(object, top);
}
}
class Driver
{
public static void main(String []args)
{
LinkedStack<String> s = new LinkedStack<String>();
s.push("A");
System.out.println(s.peek());
}
}
在此先感谢您的帮助!对此,我真的非常感激。
答
您应该只返回您的top
变量。我没有看到它初始化,但我认为它是一个类变量,因为你不用你的push方法初始化它。你可以这样做:
public Base peek()
{
if(isEmpty())
{
throw new IllegalStateException("List is empty");
}
return top.object; //this throws an error
}
+0
你太棒了!非常感谢! – awallace04
+0
我的荣幸!很高兴我能帮上忙! – BlackHatSamurai
你的推送方法是什么样的?你还在哪里打电话跑步?你意识到'Run'是一个单独的课程吗? – BlackHatSamurai
@BlackHatSamurai我知道这是一个嵌套在另一个类中的类。我编辑了原始帖子以包含我的推送方法。顶部被声明为运行对象。 – awallace04