前言
- 在做Leetcode算法题的时候,看到大神们往队列中添加元素都是用offer。看看add和offer的区别
add和offer的区别
- 截一下Jdk1.8的Queue接口中对add和offer方法的描述:(高亮部分是重点)
@return {@code true} (as specified by {@link Collection#add})
@throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
boolean add(E e);
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions.
* When using a capacity-restricted queue, this method is generally
* preferable to {@link #add}, which can fail to insert an element only
* by throwing an exception.
*
@return {@code true} if the element was added to this queue, else
{@code false}
boolean offer(E e);
- 我们可以看到add方法在添加成功的时候,返回true;但是失败的时候回抛出异常IllegalStateException;
- offer方法添加成功时返回true,失败返回false;