java - 为什么向双链表添加第二个元素时会发生堆栈溢出?

标签 java

我创建了一个双链表,它可以运行,没有任何错误。但是当我使用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/

相关文章:

java - 实现返回泛型类型的接口(interface)

java - 如何在 Eclipse 中移动条件断点?

java - 在应用程序中验证 Aadhar 卡号

java - 通过 HTTP 的 HazelCast(或在 Google AppEngine 上运行)

java - 查看 Binding with Java 11,Android Studio 总是显示错误(但运行没有任何问题)

java - jackson AfterburnerModule 在日志中发出警告

java - 如何 Autowiring RedisTemplate<String,Long>

java - 具有 ON DUPLICATE KEY UPDATE 的插入查询的 Statement 类中的executeUpdate(String sql) 方法

java - Jboss EAP 6.1 中的 RestEasy 冲突

java - Hibernate 5.0.1 最后的问题;