Search code examples
javaarrayscollectionsdequejava-6

ArrayDeque class of Deque


Since ArrayDeque class implements Deque and since it doesn't have any capacity restrictions. What is the purpose of Exception throwing methods like addFirst(), addLast(), etc? It will add the elements in any case since the array has no boundaries. Can someone please explain the with an implementation where we could use within try{}catch{} block and a scenario where addFirst could throw an exception?

try{ArrayDeque adObj = new ArrayDeque();
adObj.addFirst("Oracle");//we can keep on adding first. Use to exception handling?
}catch(Exception e){
}

Solution

  • ArrayDeque does have potential capacity problems that mean it could throw. It doubles capacity each time it is expanded so eventually it can't double any more. One implementation of the code does the following:

    private void doubleCapacity() {
        int n = elements.length;
        int newCapacity = n << 1;
        if (newCapacity < 0)
            throw new IllegalStateException("Sorry, deque too big");
    }
    

    With the definition of addFirst being as below this method can throw at least two of the exceptions described in the documentation on the interface.

    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[head = (head - 1) & (elements.length - 1)] = e;
        if (head == tail)
            doubleCapacity();
    }
    

    As others have mentioned the JavaDoc on the interface just gives possible exceptions. None of the types it throws are checked exceptions so you aren't forced to catch them.