誰:
私は、二重リンクリストを作成し、それは)それは私がのtoStringを(オーバーライドしないこのprogram.Ifを調べるために、デバッグを使用するときに、第2の要素を追加することでjava.lang.StackOverflowErrorを発生します任意のerror.Butなしで実行することができ、プログラムの意志私はtoString()をオーバーライドしない理由を知りたいnormal.Butこと?パッケージ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
}
}
ジャック:
これは、それがどのように見えるかです。ときにあなたが実行します。
System.out.println(a.first.toString());
そして、ときtoString
のように定義されます。
public String toString() {
return "Node{" +
"per=" + per +
", obj=" + obj +
", next=" + next +
'}';
}
- あなたは、次の印刷にしよう
n
n
前回の印刷での試みper
- 前の
per
印刷での再試行next
next
以前に呼び出しますper
ようにとの...
通話が終了したことがないようstackoverflowの結果として。上の画像に示すように、あなたは何度も何度も前方矢印、前の矢印で反復されています。
それを修正するには、削除することができますtoString
からNode
として置き換えます。
public String forward() {
return "Node{" +
", obj=" + obj +
", next=" + next +
'}';
}
public String backward() {
return "Node{" +
", obj=" + obj +
", prev=" + per +
'}';
}