toString Override in Java

后端 未结 6 1999
悲哀的现实
悲哀的现实 2021-01-25 09:12

This question is from an assignment. I have to override a toString() method in a class that creates a circularly linked list and I actually have a toString() method that works g

6条回答
  •  鱼传尺愫
    2021-01-25 09:57

    Use StringBuilder instead may do your a favor.This is snippet is copied from AbstractCollection.toString(),take a look at it.

     public String toString() {
        Iterator i = iterator();
    if (! i.hasNext())
        return "[]";
    
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = i.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! i.hasNext())
        return sb.append(']').toString();
        sb.append(", ");
    }
    }
    

提交回复
热议问题