Differnce between addfirst and offerFirst methods in ArrayDeque

后端 未结 2 1215
悲&欢浪女
悲&欢浪女 2021-01-04 19:23

Have tried out a sample program to understand the difference between addFirst and offerFirst methods in ArrayDeque of Java 6. But they

相关标签:
2条回答
  • 2021-01-04 20:01

    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.

    0 讨论(0)
  • 2021-01-04 20:12

    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 ...

    0 讨论(0)
提交回复
热议问题