Printing out a linked list using toString

后端 未结 5 1583
耶瑟儿~
耶瑟儿~ 2020-12-06 13:19

Ok guys, so I am trying to learn how to print out a linked list. I have all the methods that I would need to use for the list, but I can\'t figure out how to display the va

5条回答
  •  失恋的感觉
    2020-12-06 13:54

    When the JVM tries to run your application, it calls your main method statically; something like this:

    LinkedList.main();
    

    That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

    So the body of your main method should be like this:

    public static void main(String[] args){
        // creating an instance of LinkedList class
        LinkedList ll = new LinkedList();
    
        // adding some data to the list
        ll.insertFront(1);
        ll.insertFront(2);
        ll.insertFront(3);
        ll.insertBack(4);
    
        System.out.println(ll.toString());
    }
    

提交回复
热议问题