LinkedList Java traverse and print

后端 未结 4 1792
轮回少年
轮回少年 2020-12-20 07:41

I would really appreciate if you can help to answer to this question:

I have already created a custom linked list myself in a very standard way using Java. Below are

相关标签:
4条回答
  • 2020-12-20 08:05

    Your getData() in Node class returns an Object type. You need to cast it into a String so that it gets printed by println() properly.

    System.out.println((String)tmp.getData());

    should do the trick for you.

    0 讨论(0)
  • 2020-12-20 08:10

    You need to override the toString() method on Node:

    @Override
    String toString() {
      String val = // however you want to represent your Node
      return val;
    }
    

    and print the node:

    System.out.println(tmp);
    

    Alternatively, have Node.getData() return a String if you know you are only going to store Strings -- change the Objects to String in the Node definition

    Alternatively, you could use generics to specify the type of data inside the node

    UPDATE: after a little more thought (provoked by comments), I see something amiss:

    tmp.getData() should return a string (based on Node's single parameter ctor and that you are passing strings), but the output is about references to Node objects. Is it possible that linkedList.add re-sets the Node's obj member to a Node instead?

    0 讨论(0)
  • 2020-12-20 08:15

    The LinkedList is of Objects, Objects toString method prints out the reference. If you want to print out the string you are going to have either change the LinkedList to a String/Generics or cast the print out like this:

    String output = (String)tmp.getData();
    System.out.println(output);
    

    (you can do this in one line if you want).

    0 讨论(0)
  • 2020-12-20 08:19

    Your linkedList class already creates the Nodes for you!

    linkedList list = new linkedList();
    list.add("foo");
    list.add("bar");
    Node tmp = lst.getHead();
    while(tmp != null){
        System.out.println(tmp.getData());
        tmp = tmp.getNext();
    }
    

    Will print

    foo
    bar
    
    0 讨论(0)
提交回复
热议问题