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

前端 未结 9 1522
南方客
南方客 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:51

    I recommend using ToStringBuilder from Apache Commons Lang. Internally it uses a ThreadLocal Map to "detect cyclical object references and avoid infinite loops."

提交回复
热议问题