[英]Writing my own peek() method for my own LinkedList class in Java
So I've been asked to write a peek()
method for a linked list in Java. 因此,有人要求我为Java中的链表编写一个
peek()
方法。 The only thing is that the object I want to "peek" is a private variable of type base that exists in a private class within my LinkedList class. 唯一的事情是我要“窥视”的对象是存在于我的LinkedList类的私有类中的base类型的私有变量。 I would like to use my
peek()
method to return the object and print it out. 我想使用我的
peek()
方法返回对象并打印出来。 I know this has something to do with accessing a private variable but I can't quite make it work with what I have. 我知道这与访问私有变量有关,但是我不能完全使它与我拥有的东西一起工作。 Here is a snippet of my code:
这是我的代码片段:
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());
}
}
Thanks in advance for any help! 在此先感谢您的帮助! I really appreciate it.
我真的很感激。
You should just return your top
variable. 您应该只返回
top
变量。 I don't see it initialized, but I assume it's a class variable since you don't initialize it in your push method. 我看不到它已初始化,但我认为它是一个类变量,因为您没有在push方法中对其进行初始化。 You could then do:
然后,您可以执行以下操作:
public Base peek()
{
if(isEmpty())
{
throw new IllegalStateException("List is empty");
}
return top.object; //this throws an error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.