java - 为什么 toString 方法在这里不起作用?

标签 java linked-list tostring

这是我的整个类(class),我已将数字 2 添加到双向链表中,然后我希望将其打印在控制台中,但它会显示此“datastructureproject.Node@f62373” 谢谢!

package datastructureproject;

public class DoublyLinkedList {
private Node head = new Node(0);
private Node tail = new Node(0);
private int length = 0;

public DoublyLinkedList() {

    head.setPrev(null);
    head.setNext(tail);
    tail.setPrev(head);
    tail.setNext(null);
}

public void add(int index, int value) throws IndexOutOfBoundsException {
    Node cursor = get(index);
    Node temp = new Node(value);
    temp.setPrev(cursor);
    temp.setNext(cursor.getNext());
    cursor.getNext().setPrev(temp);
    cursor.setNext(temp);
    length++;
}

private  Node get(int index) throws IndexOutOfBoundsException {
    if (index < 0 || index > length) {
        throw new IndexOutOfBoundsException();
    } else {
        Node cursor = head;
        for (int i = 0; i < index; i++) {
            cursor = cursor.getNext();
        }
        return cursor;
    }
}

public long size() {
    return length;
}

public boolean isEmpty() {
    return length == 0;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("(head) - ");
Node temp = head;
while (temp.getNext() != tail) {
    temp = temp.getNext();
    result.append(temp.getValue() + " - ");
}
result.append("(tail)");
return result.toString();
}

public static void main(String[] args){
    DoublyLinkedList list = new DoublyLinkedList();
    list.add(0,2 );
    System.out.println(list.get(0).toString());
    }
}

已编辑:这也是我的 Node 类,谢谢!

class Node {

public int value;

public Node(){

}

public void setValue(int value) {
    this.value = value;
}
public Node next;
public Node prev;

public Node(int value) {
    this.value = value;
}

public Node(int value, Node prev, Node next) {
    this.value = value;
    setNext(next);
    setPrev(prev);
}

public void setNext(Node next) {
    this.next = next;
}

public void setPrev(Node prev) {
    this.prev = prev;
}

public Node getNext() {
    return next;
}


public Node getPrev() {
    return prev;
}

public int getValue() {
    return value;
}
}

最佳答案

您已经覆盖了 DoubleLinkedList 上的 toString(),但您是在 Node 上调用它。如果您只想打印节点的内容,请调用 list.toString() 或覆盖 Node.toString()

关于java - 为什么 toString 方法在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2938170/

相关文章:

java - 我们可以从 Wicket Java 类调用 html id吗

java - 如何检查字符串中是否只出现某些字符?

c - C中的节点和链表语法

java - JDO 使用列表查询列表

c - 在C中删除链表中的重复项不起作用

algorithm - 为什么在给定要删除的节点时,单链表和双链表中的删除操作都不为 O(1)?

php - PHP echo 语句中的无限递归

Java toString() - 是否在 toString 中包含类名?

MongoDB将数字转换为科学计数法的字符串

java - 两个具有相同编号的构造函数。参数但不同的数据类型