Java:"JAR文件没有附件"错误,但仅当我覆盖toString()方法时

Iva*_*Iva 0 java exception tostring

我编写了一个名为Node的类,它表示图中的节点.它看起来像这样:

public class Node{
    protected ArrayList<Node> neighbours = new ArrayList<>();

    public Node(ArrayList<Node> neighbours){
        for(int i=0;i<neighbours.size();i++){
            this.neighbours.add(neighbours.get(i));
        }
    }
    public Node(){}
    public void setNeighbours(ArrayList<Node> neighbours){
        this.neighbours.clear();
        this.neighbours.addAll(neighbours);
    }
    public ArrayList<Node> getNeighbours(){
        return this.neighbours;
    }
    @Override
    public String toString(){
        String s = new String(""+this.neighbours);  
        return s;   
    }
}
Run Code Online (Sandbox Code Playgroud)

我在覆盖toString方法之前测试了它,创建了一个基本图形.输出是正确的,唯一的问题是输出是每个对象的地址,而不是对象本身(Node@61672c01例如).在编写toString方法之后,我开始收到诸如"源文件没有附件"和java.lang.StackOverflowError错误等大量错误

我尝试更改项目的构建路径(我认为错误的构建类型是原因),但这没有帮助.我认为递归java.lang.StackOverFlowError有问题,因为,但在编写toString()方法之前没有任何问题.

Sur*_*tta 5

你处于永不停止的递归循环中.

 String s = new String(""+this.neighbours);  
Run Code Online (Sandbox Code Playgroud)

这是你的列表在每个节点上打印toString.

然后toString()再来list打印.