这是我的整个类(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/