我创建了一个双链表,它可以运行,没有任何错误。但是当我使用debug检查这个程序时,在添加第二个元素时会出现java.lang.StackOverflowError。如果我不重写toString(),程序将正常。但我想知道为什么不重写toString()? 包 com.study.testcollection.com.study.teSTLinkedlist;
public class Node {
private Node per;
private Object obj;
private Node next;
public Node getPer() {
return per;
}
public Object getObj() {
return obj;
}
public Node getNext() {
return next;
}
public void setPer(Node per) {
this.per = per;
}
public void setObj(Object obj) {
this.obj = obj;
}
public void setNext(Node next) {
this.next = next;
}
@Override
//if don't write this function,the program will be normal.Why?
public String toString() {
return "Node{" +
"per=" + per +
", obj=" + obj +
", next=" + next +
'}';
}
}
package com.study.testcollection.com.study.testlinkedlist;
public class Mylinkedlist {
Node first = null;
Node last = null;
public void add(Object e){
if (first == null){
Node n = new Node();
n.setObj(e);
n.setPer(null);
n.setNext(null);
first = n;
last = n;
}
else{
Node n = new Node();
n.setObj(e);
last.setNext(n);
n.setPer(last);
n.setNext(null);
last = n;
}
}
public static void main(String[] args) {
Mylinkedlist a = new Mylinkedlist();
a.add("hello");
a.add("Bob");//occur error when it is executed
}
}
最佳答案
你的“next”字段指向一个 Node,因此 Node.toString() 被无限调用,导致堆栈溢出。 如果需要使用toString()方法,可以修改如下:
public String toString() {
String n = next != null ? next.obj.toString():"null";
String p = per != null ? per.obj.toString():"null";
return "Node{" +
"per=" + p +
", obj=" + obj +
", next=" + n +
'}';
}
关于java - 为什么向双链表添加第二个元素时会发生堆栈溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741491/