简体   繁体   中英

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. 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.

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM