10

Have tried out a sample program to understand the difference between addFirst and offerFirst methods in ArrayDeque of Java 6. But they seem to be same, any suggestions?

public void interfaceDequetest()
{
        try{
        ArrayDeque<String> ad = new ArrayDeque<String>();
        ad.addFirst("a1");
        ad.offerFirst("o1");
        ad.addFirst("a2");
        ad.offerFirst("02");
        ad.addFirst("a3");

        System.out.println("in finally block");

        for (String number : ad){
            System.out.println("Number = " + number);
        }
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
user288686
  • 135
  • 2
  • 11

2 Answers2

15

The difference is what happens when the addition fails, due to a queue capacity restriction:

  • .addFirst() throws an (unchecked) exception,
  • .offerFirst() returns false.

This is documented in Deque, which ArrayDeque implements.

Of note is that ArrayDeque has no capacity restrictions, so basically .addFirst() will never throw an exception (and .offerFirst() will always return true); this is unlike, for instance, a LinkedBlockingQueue built with an initial capacity.

fge
  • 119,121
  • 33
  • 254
  • 329
4

the source code of offerFirst :

 public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

And addFirst

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

offerFirst returns true, thats the only difference ...

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311