java - linkedList 的 toString 方法

标签 java junit linked-list tostring

我在 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/

相关文章:

java - 如何检测-鼠标右键还是左键为主?

java - 如何避免 '@RepeatedTest Annotation runs BeforeEach and AfterEach in JUnit' ?

google-app-engine - 无法在 GWT 上对 RPC 进行单元测试

java - 使用可操作和不可操作的静态类进行测试

c++ - 比较模板变量的值

java - 缺少方法体,或在 Java 中声明抽象

java将字符添加到字符串中

c - 为什么这些代码片段的行为不同?

java - 如何在 Android Studio 中实现折叠文本?

java - 在 LinkedList 中添加一个点而不覆盖另一个点 - Java