Most efficient way to prevent an infinite recursion in toString()?

前端 未结 9 1472
南方客
南方客 2020-12-15 21:20

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

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 21:43

    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.

提交回复
热议问题