[英]Recursion - Exception in thread “main” java.lang.StackOverflowError during linked-list reversal
[英]java.lang.stackoverflowerror when adding to a Linked-List
我在嘗試將object添加到鏈表(java util )時遇到了這個問題
public abstract class Person {
private LinkedList<Appointment> scheduledAppointments = new LinkedList<Appointment>();
//irrelevant code
public boolean addAppointment(Appointment appointment){
return this.scheduledAppointments.add(appointment);
}
參與者屬性在鏈表中有一個醫生和一個病人。
public class Appointment {
private ArrayList<Person> participants = new ArrayList<Person>();
...
public Appointment(Person doctor, Person patient, int day, int month, int year, double startHour, Procedure procedure) {
this.participants.add(doctor);
this.participants.add(patient);
...
}
public void addAppointmentToParticipants(){
for (Person person : participants) {
person.addAppointment(this);
}
}
當我嘗試將約會添加到每個參與者時會出現問題: Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate Appointment.toString()
Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate Appointment.toString()
當我調試它時,我可以看到異常發生在 LinkedList.java 上,特別是在size++ 行
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
我不明白為什么我會遇到這個問題,以及“toString”與它有什么關系......
根據錯誤消息中的toString()
,看起來您在Appointment
中擁有的任何toString()
都嵌入了Person
的字符串表示,但在Person
中擁有的任何toString()
都對Appointment
做同樣的事情。 任何時候調用toString()
都會導致StackOverflowError
,因為字符串會不斷擴展(並且這里的關系是雙向的)。
這也將使您無法在不遇到錯誤的情況下打印出LinkedList
。
解決方案是使這些類之一的toString()
不嵌入另一個類的toString()
。 更好的是,您應該重新考慮您的 model 並確定您是否真的需要這種雙向關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.