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

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

    You can create toString which takes an identity hash set.

    public String toString() {
       return toString(Collections.newSetFromMap(new IdentityHashMap()));
    }
    
    private String toString(Set seen) {
       if (seen.add(this)) {
          // to string this
       } else {
          return "{this}";
       }
    }
    
        

    提交回复
    热议问题