que:
He creado una lista ligada doble y puede funcionar sin ningún tipo de error.But ocurrirá java.lang.StackOverflowError en adición segundo elemento cuando uso de depuración para examinar esta program.If i no anulan toString (), el programa ser normal.But quiero saber por qué no anulan toString ()? com.study.testcollection.com.study.testlinkedlist empaquetar;
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
}
}
Jack:
Esto es lo que parece. Cuando tu lo hagas :
System.out.println(a.first.toString());
Y cuando toString
se define como:
public String toString() {
return "Node{" +
"per=" + per +
", obj=" + obj +
", next=" + next +
'}';
}
- Se intenta en la impresión de la siguiente que es
n
n
intentos en la impresión de la anteriorper
- Anteriores
per
intentos de nuevo en la impresiónnext
next
hace un llamado a la anteriorper
y así sucesivamente ...
Lo que resulta en stackoverflow como la llamada nunca termina. Usted está iterando una y otra vez en la flecha hacia adelante y la flecha anterior como se muestra en la imagen de arriba.
Para solucionarlo, puede quitar toString
desde Node
y sustituir por:
public String forward() {
return "Node{" +
", obj=" + obj +
", next=" + next +
'}';
}
public String backward() {
return "Node{" +
", obj=" + obj +
", prev=" + per +
'}';
}