Java - Deque手册 - 删除最后一个

时间:2013-03-20 16:38:11

标签: java deque

我在java中有一些功课来实现deque系统。我已经创建了其他方法,他们通过了我的测试。但是我在移除最后一个问题上遇到了问题。到目前为止,我有这个;

//remove the element at the back of the deque
public int removeBack()
{
    int size = a.size();
    size--;

    if( size > 0 )
    {
        int last = a.get(size);
        last--;
        a.remove(last);
    }

    size = a.size();

    return size;
}

这是它失败的JQuery测试。

    Deque d = new Deque(1);
    d.insertBack(1);
    assertEquals(1, d.length());
    int b = d.removeBack();
    assertEquals(0, b);
    // java.lang.AssertionError: expected:<1> but was:<0>

有人有什么想法吗?我真的看不出这个问题出在哪里。

干杯

2 个答案:

答案 0 :(得分:1)

你的代码很乱。

d.insertBack(1);   <---- you add one element.
assertEquals(0, d.length()); <--- length is expected to be 1
int b = d.removeBack();  <---- you remove one element, and return the new length (!)
assertEquals(1, b); <----- b = length after removing = 0

你可能想做什么:

public int removeBack() {
    return a.remove(a.size() - 1); // Remove and return last element.
}

(注意:返回最后一个元素是标准的,而不是列表大小,必要时可以size()查询。)

答案 1 :(得分:0)

以下是iffy:

    int last = a.get(size);
    last--;
    a.remove(last);

无论你是否期望ArrayList.remove(int)获取索引或值(它需要索引),我都看不出这是如何工作的。