Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differnce between addfirst and offerFirst methods in ArrayDeque

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);
        }
}
like image 727
user288686 Avatar asked Mar 10 '14 06:03

user288686


1 Answers

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.

like image 169
fge Avatar answered Sep 29 '22 05:09

fge