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

前端 未结 8 1471
盖世英雄少女心
盖世英雄少女心 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 14:02

    Source: http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html

    The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

    0 讨论(0)
  • 2020-12-12 14:03

    The difference is following:

    • offer method - tries to add an element to a queue, and returns false if the element can't be added (like in case when a queue is full), or true if the element was added, and doesn't throw any specific exception.

    • add method - tries to add an element to a queue, returns true if the element was added, or throws an IllegalStateException if no space is currently available.

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