add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.
offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.
区别:两者都是往队列尾部插入元素,不同的是,当超出队列界限的时候,add()是抛出异常让你处理,而offer()是直接返回false。
leetcode一般用offer()。
同理
- Queue 中 remove() 和 poll()有什么区别?
Queue 中 remove() 和 poll()都是用来从队列头部删除一个元素。
在队列元素为空的情况下,remove() 方法会抛出NoSuchElementException异常,poll() 方法只会返回 null 。