Differnce between addfirst and offerFirst methods in ArrayDeque

拜拜、爱过 提交于 2019-11-30 03:15:22

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/22293468/differnce-between-addfirst-and-offerfirst-methods-in-arraydeque

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!