我在 linkedList 类中得到了奇怪的 toString 输出。
我不能使用任何方法,只能使用字符串连接。如何解决这个问题非常有限。
这是代码:
@Override
public String toString() {
if (head == null) {
return "";
}
String result = "";
Node curr = head;
while (curr.next != null) {
curr = curr.next;
result += curr.data + ", ";
}
return result;
}
我编写了一个 JUnit 测试:
assetsEquals(
"8,6,7,5,3,0,9, " + "9,0,3,5,7,6,8", dataTest.noOrderList().toString());
noOrderList().toString() 来自:
public static noOrderList<Integer> noOrderList() {
return makeListInNoOrder(new Integer[]{ 8, 6, 7, 5, 3, 0, 9, 9, 0, 3, 5, 7, 6, 8});
当我运行测试时,我得到:
expected:<... 3, 0, 9, 9, 0, 3[]> but was: <... 3, 0, 9, 9, 0, 3[, ]>
这是造成这种情况的原因,在 [, ] 中如何消除该逗号?
谢谢
最佳答案
您始终将 ", "
字符串附加到结果中。
- 因此,对于第一个元素,您需要附加
"9, "
。 - 对于第二个,它是
“0,”
- 等等...
- 最后,添加
"3, "
作为最后一个。
相反,仅当下一个元素不为 null
时,才应附加 ", "
。
例如:
while (curr.next != null) {
curr = curr.next;
result += curr.data;
if (curr.next != null)
result += ", ";
}
为了保存一些比较,您应该在元素之前发出 ", "
,并在循环之前发出第一个元素:
//don't print head, since that seems to be empty in your implementation.
//also make sure head does not reference `null` by accident...
if (curr.next == null)
return result;
curr = curr.next;
//1st element after `head`
result += curr.data;
while (curr.next != null) {
curr = curr.next;
result += ", " + curr.data;
}
我还注意到您从未将 head
元素放入结果中。是空的还是错误?
关于java - linkedList 的 toString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42676579/