gpt4 book ai didi

Java 记录 StackOverflow RuntimeException

转载 作者:行者123 更新时间:2023-12-01 12:42:39 25 4
gpt4 key购买 nike

我正在学习 Java 记录、预览功能,并且在运行以下代码时遇到 StackOverflow 异常。

    import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public record Course(String name, Student topper) { }
public record Student(String name, List<Course> enrolled) {}

public static void main(String[] args) {
Student john = new Student("John", new ArrayList<>());
john.enrolled().add(new Course("Enrolled for Math", john));
john.enrolled().add(new Course("Enrolled for History", john));
System.out.println(john);
}
}


Below is the exception trace :


java --enable-preview Example
Exception in thread "main" java.lang.StackOverflowError
at Example$Course.toString(Example.java:6)
at java.base/java.lang.String.valueOf(String.java:3388)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)

从异常中我意识到它与 toString() 有关,当我在记录中覆盖 toString() 如下代码时,我没有看到 Exception 。
// code with implementation of toString()
public class Example {

public record Course(String name, Student topper) {
public String toString()
{
return name;
}
}
public record Student(String name, List<Course> enrolled) {
public String toString()
{
return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
}
}
public static void main(String... args) {
Student john = new Student("John", new ArrayList<>());
john.enrolled().add(new Course("Enrolled for Math", john));
john.enrolled().add(new Course("Enrolled for History", john));
System.out.println(john);
}
}

此代码打印 John : Enrolled for Math,Enrolled for History 。有人可以解释为什么如果我不覆盖 toString() 会得到 StackOverflow?当我打印 john.hashCode() 时,我也看到 StackOverflow

最佳答案

Record#toString无关特别是。仔细看看你的声明:

public record Course(String name, Student topper) {}
public record Student(String name, List<Course> enrolled) {}
Course#toString需求 Student#toStringStudent#toString需求 Course#toString .因此,如果您尝试打印 Student那么全部报名 Course将一起打印。那些 Course s 需求 Student所以他们会打印 Student里面。这个循环会一直持续到你得到 StackOverflow异常(exception)。

为避免这种情况,您应该重新排列代码,使它们不相互依赖。您可以为每个实例创建一个 ID。一个例子是:
public record Course(String name, String studentId) {}
public record Student(String name, String studentId, List<Course> courses) {}

关于Java 记录 StackOverflow RuntimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62147477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com