Reputation: 131
So I've been asked to write a peek()
method for a linked list in Java. 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. I would like to use my peek()
method to return the object and print it out. 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.
Upvotes: 0
Views: 2027
Reputation: 23503
You should just return your top
variable. I don't see it initialized, but I assume it's a class variable since you don't initialize it in your push method. You could then do:
public Base peek()
{
if(isEmpty())
{
throw new IllegalStateException("List is empty");
}
return top.object; //this throws an error
}
Upvotes: 2