首页 > 解决方案 > 为什么将第二个元素添加到双链表时会发生堆栈溢出?

问题描述

我创建了一个双链表,它可以毫无错误地运行。但是当我使用调试检查这个程序时,添加第二个元素时会出现 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
    }
}

标签: java

解决方案


您的“下一个”字段指向一个节点,因此 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 +
                '}';
    }

推荐阅读