我有一个链接列表的toString方法,它以类似时尚的方式打印出来,但它也打印出多余的字符。如何摆脱最后的", "
?
public String toString() {
String ret = "[";
Node current = head;
while(current.getNext() != null) {
current = current.getNext();
ret += current.get() + ", ";
}
return ret + "]";
}
示例:我们有一个包含3个元素的链表,然后我们将其打印出来。
"[1, 2, 3, ]"
答案 0 :(得分:2)
我没有测试它,但这应该有效。
public String toString() {
String ret = "[";
Node current = head;
while(current.getNext() != null) {
current = current.getNext();
ret += current.get();
if(current.getNext() != null) ret += ", ";
}
return ret + "]";
}
答案 1 :(得分:2)
我使用Apache Commons Lang - StringUtils和ArrayList来返回字符串而不会过多。看看我如何使用它:
public String toString() {
List<String> ret = new ArrayList<String>();
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
ret.add(current.get());
}
return "[" + StringUtils.join(ret, ",") + "]";
}
答案 2 :(得分:1)
您可以使用substring
删除最后2个字符。
return ret.substring(0, ret.length()-2)+"]"
答案 3 :(得分:0)
public String toString() {
StringBuilder ret = new StringBuilder('[');
Node current = head;
while(current.getNext() != null) {
current = current.getNext();
ret.append(current.get()).append(", ");
}
if (ret.length() > 1) {
ret.delete(ret.length() - 2, ret.length());
}
return ret.append(']').toString();
}
必须保护一个空列表,使其保持[]
。这留下了两种可能性:布尔标志或之后删除。为了提高性能,请使用StringBuilder。在某种程度上,编译器会将String连接转换为StringBuilder,但这并非完全如此。
答案 4 :(得分:0)
使用此ret.substring(0, ret.length() - 1)
@Override
public String toString() {
String ret = "[";
Node current = head;
while(current.getNext() != null) {
current = current.getNext();
ret += current.get() + ", ";
}
ret = ret.substring(0, ret.length() - 1);
return ret + "]";
}
答案 5 :(得分:0)
也许您应该考虑查看toString()
Javas AbstractCollection
方法。这将为您提供如何使用StringBuilder实现此目的的好主意:
/**
* Returns a string representation of this collection. The string
* representation consists of a list of the collection's elements in the
* order they are returned by its iterator, enclosed in square brackets
* (<tt>"[]"</tt>). Adjacent elements are separated by the characters
* <tt>", "</tt> (comma and space). Elements are converted to strings as
* by {@link String#valueOf(Object)}.
*
* @return a string representation of this collection
*/
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
答案 6 :(得分:0)
试试这个:
public String toString() {
String ret = "[";
Node current = head;
while(current.getNext() != null) {
current = current.getNext();
ret += current.get() + ", ";
}
ret=ret.substring(0,ret.length()-2);
return ret + "]";
}