简体   繁体   中英

java.lang.stackoverflowerror when adding to a Linked-List

I'm getting this problem while trying to add an object to a linkedlist (java util) I've a Doctor and Patient class, both inherit from the abstract class Person

public abstract class Person {
    private LinkedList<Appointment> scheduledAppointments = new LinkedList<Appointment>();

    //irrelevant code

    public boolean addAppointment(Appointment appointment){
        return this.scheduledAppointments.add(appointment);
    }

the participants attribute has a doctor and a patient in the linked list.

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);
        }
    }

the problem occurs when i'm trying to add the Appointment to each of the participants: Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate Appointment.toString() Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate Appointment.toString()

when I'm debugging it, i can see that the exception occurs on the LinkedList.java, particularly on the size++ line

   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++;
    }

I don't understand why i'm haing this problem, and what does "toString" has to do with it...

Based on the toString() in the error message, it looks like whatever toString() you have in Appointment embeds the string representation of Person , but whatever toString() you have in Person does the same for Appointment . This would lead to a StackOverflowError anytime you call toString() , because the string would continually expand (and the relationship is bi-directional here).

This would also make printing out your LinkedList impossible without encountering the error.

The solution is to make the toString() of one of these classes not embed the other's toString() . Better yet, you should rethink your model and determine whether you really need this bi-directional relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM