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 楼答案
对我来说,问题在于:
由于调用了两次“getNextNode()”,因此错过了一个元素,assertEquals将不匹配