offer()
返回 boolean
,而如果 Queue
中没有元素,add()
会抛出 Exception
。那么,一般应该使用哪一种以及使用其中一种相对于另一种有哪些优势?
最佳答案
我想区别在于契约(Contract),当元素无法添加到集合中时,add 方法会抛出异常,而 Offer 不会。
来自:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#add%28E%29
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:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29
Inserts the specified element into this queue, if possible. 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.
来源:- What is the difference between the add and offer methods in a Queue in Java?
关于java - Queue#offer() 应该优先于 Queue#add() 吗?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860018/