有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在toString方法中将对象转换为特定数据类型

因此,下面方法中的node.getValue()返回一个E或泛型数据类型

public String toString() {
    StringBuilder linkedQueueAsString = new StringBuilder();
    linkedQueueAsString.append("< ");
    for (Link<E> node = this.front.getNextNode(); node != null; node = node.getNextNode())    
    {
        linkedQueueAsString.append(node.getValue()); // <=== Not working correctly
        linkedQueueAsString.append(" ");
    }
    linkedQueueAsString.append(">");
    return linkedQueueAsString.toString();
}

当我像下面这样测试时,我的测试失败了:

public void setUp() {
    this.queue1 = new LinkedQueue<Integer>();
    this.queue2 = new LinkedQueue<Integer>();
}

public void test_enqueue3IntegersAndThenDequeueThem() {
    this.queue2.enqueue(1);
    this.queue2.enqueue(2);
    this.queue2.enqueue(3);
    assertEquals(3, this.queue2.length());
    assertEquals("< 1 2 3 >", this.queue2.toString()); // <= ERROR since none of the numbers printed out

}

您可以看到我对链接队列here的个人实现

我该怎么解决这个问题?谢谢


共 (1) 个答案

  1. # 1 楼答案

    对我来说,问题在于:

     for (Link<E> node = this.front.getNextNode(); node != null; node = node.getNextNode()) {
    

    由于调用了两次“getNextNode()”,因此错过了一个元素,assertEquals将不匹配