I have a StackOverflowError in Java and it doesn’t tell me any line in my own code, the relevant part of the stacktrace is:
java.lang.StringBuilder.append(StringBuilder.java:132)
java.util.AbstractMap.toString(AbstractMap.java:523)
java.lang.String.valueOf(String.java:2838)
java.lang.StringBuilder.append(StringBuilder.java:132)
java.util.AbstractCollection.toString(AbstractCollection.java:439)
java.lang.String.valueOf(String.java:2838)
I’ve tried getting the stack trace from the throwable, but for some reason it doesn’t contain the relevant nodes, I’m trying to find some inpoint in my code as to where the error is. Also I’ve tried to reduce the stack size to 128k to get the error earlier, no avail.
For a
StackOverFlowError, the stack trace is often truncated (since it is too long), which does not really help finding the error.In your case, assuming the part you copied is the one which is repeating, it looks like you added a map to a collection, which in turn is a as a key or value of the original map, and then use the
toString()method on one of these objects.The default implementation of
toString()for a map (in AbstractMap) then callsStringBuilder.append(...)with all its keys and values, which in turn will invoketoStringon these. For AbstractCollection, the same is valid for the elements of the collection.(The example in Jon’s answer does a similar thing with two collections instead of a map and a collection.)
Solutions:
toString()(andhashCode/equals, too), ortoString()method of one of them to break the cycle.