What is the difference between the add and offer methods in a Queue in Java?

前端 未结 8 1474
盖世英雄少女心
盖世英雄少女心 2020-12-12 13:29

Take the PriorityQueue for example http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)

Can anyone give me an example of a Queu

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 13:53

    The difference between offer and add is explained by these two excerpts from the javadocs:

    From the Collection interface:

    If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

    From the Queue interface

    When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.

    PriorityQueue is a Queue implementation that does not impose any insertion restrictions. Therefore the add and offer methods have the same semantics.

    By contrast, ArrayBlockingQueue is an implementation in which offer and add behave differently, depending on how the queue was instantiated.

提交回复
热议问题