Search code examples
javadeque

Java - Deque manual - Remove Last


I've got some homework to in java to implement a deque system. I've created the other methods and they pass my tests. However I'm having a issue with removing the last one. I have this so far;

//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;
}

Here is the JQuery test it fails on.

    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>

Anyone have any ideas? I really can't see where I'm going wrong with this one.

Cheers


Solution

  • Your code is a mess.

    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
    

    What you probably meant to do:

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

    (Note: it is standard to return the last element, not the list size, which can be queried by size() when necessary.)