問題描述
在使用PriorityQueue類的時候下面有offer和add方法都是用來在堆中插入元素,但是看一下add源碼
/**
* Inserts the specified element into this priority queue.
*
* @return {@code true} (as specified by {@link Collection#add})
* @throws ClassCastException if the specified element cannot be
* compared with elements currently in this priority queue
* according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return offer(e);
}
返回的還是offer方法,這不就是多此一舉了嗎,可是去搜索的結果的是告訴我這倆是有區別的
兩者都是往隊列尾部插入元素,不同的時候,當超出隊列界限的時候,add()方法是拋出異常讓你處理,而offer()方法是直接返回false
但是我不知道怎么看這倆個有這個區別,我只知道add方法繼承的Collection方法,offer是實現的Queue接口
希望如果有大牛路過的話可以在評論區評論分享技術,各自努力,你我最高處見