I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .
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)
From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the 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);
}
}
This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()