To string on a collection can get into a infinite loop if somewhere in the graph of collected items is a reference back to itself. See example below.
Yes, good cod
The problem is not inherent to collections, it can happen with any graph of objects that have cyclic references, e.g., a doubly-linked list.
I think that a sane policy is: the toString()
method of your class should not call toString()
of its children/referenced if there is a possibility that it's part of a object graph with cycles. Elsewhere, we could have a special methods (perhaps static, perhaps as an auxiliary class) that produces a string representation of the full graph.