java - 为什么将第二个元素添加到双链表时会发生堆栈溢出?
问题描述
我创建了一个双链表,它可以毫无错误地运行。但是当我使用调试检查这个程序时,添加第二个元素时会出现 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
}
}
解决方案
您的“下一个”字段指向一个节点,因此 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 +
'}';
}
推荐阅读
- apache-spark - 转换 DataFrame 格式
- javascript - 在momentjs中将日期从一个时区转换为另一个时区
- python - 有没有办法找到不共享任何项目的列表列表的所有组合?
- amazon-web-services - 由于缺少角色权限,无法执行 config:PutEvaluations
- r - 问题:线性回归中一个因子的每个值的系数
- ansible - 从模板部署时将新 Windows 来宾加入域的正确方法
- node.js - 如何从downloadurl获取firebase存储位置?
- julia - 使用 JIT 编译器的 julia 工作流
- c# - 在转换和访问 DataContext 对象时,为什么我们必须放括号?
- python - 在 Python 中将一种数据模式拟合到另一种数据模式