toStrings()的堆栈溢出错误(java)

时间:2014-10-24 05:02:21

标签: java recursion tostring stack-overflow

我的两个toString()&#s;似乎处于无限循环中,但我不确定问题是什么。我现在已经调试了好几个小时了,看不出任何错误。

对于上下文,主要的相关部分是:     的System.out.println(1类);     adminStaff1.assignInstructor(class1,instructor1);     的System.out.println(1类);

第一个println有效,但是当我调试时,我会看到一个源查找错误,然后才能通过。第二个class1创建StackOverflowError,它是:

Exception in thread "main" java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at java.lang.StringBuilder.<init>(Unknown Source)
at Instructor.toString(Instructor.java:59)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at Class.toString(Class.java:89)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at java.util.AbstractCollection.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at Instructor.toString(Instructor.java:59)

Class的toString是:

@Override
public String toString() {
    return "Class [instructor=" + instructor + ", lectureHall="
            + lectureHall + ", currentEnrollment=" + currentEnrollment
            + ", timeSlot=" + timeSlot + ", filled=" + filled
            + ", studentList=" + studentList + "]";
}

教师的toString是:

@Override
public String toString() {
    return "Instructor [salary=" + salary + ", classList=" + classList
            + ", openTimeSlots=" + openTimeSlots + ", "
            + super.toString() + "]";
}

和super.toString()是:

@Override
public String toString() {
    return "[idNumber=" + idNumber + ", email=" + email
            + "]";
}

我不确定原因,但是adminStaff1.assignInstructor似乎也在解决这个问题,它是:

public void enrollStudent(Student student, Class aClass){
    aClass.checkIfFilled();
    if(!aClass.getFilled()){
        aClass.addStudent(student);
        student.addClass(aClass);
        aClass.increaseEnrollment();
    } else {
        System.out.println("Could not add student because the class is currently full.");
    }
}

如果有人能帮我理解错误,我真诚地感谢。感谢。

1 个答案:

答案 0 :(得分:4)

当您在toString()上致电Class时,其中包含InstructorInstructor包含Class)。这是一个循环。打破它,

return "Instructor [salary=" + salary + /* ", classList=" + classList */
        + ", openTimeSlots=" + openTimeSlots + ", "
        + super.toString() + "]";

或者,

return "Class [lectureHall=" + lectureHall + ", currentEnrollment=" 
        + currentEnrollment + ", timeSlot=" + timeSlot + ", filled=" + filled
        + ", studentList=" + studentList + "]";