Java 隊列的`add()`方法和`offer()`方法的區別


查閱API文檔,找到

add():增加一個元素。如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常

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():添加一個元素並返回true。如果隊列已滿,則返回false

Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

分析

  • 兩者都是往隊列尾部插入元素
  • 當超出隊列界限的時候,add()方法是拋出異常讓你處理,而offer()方法是直接返回false

Java隊列的部分調用方法

方法 作用 說明
add() 增加一個元素 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
remove() 移除並返回隊列頭部的元素 如果隊列為空,則拋出一個NoSuchElementException異常
element() 返回隊列頭部的元素 如果隊列為空,則拋出一個NoSuchElementException異常
offer() 添加一個元素並返回true 如果隊列已滿,則返回false
poll() 移除並返問隊列頭部的元素 如果隊列為空,則返回null
peek() 返回隊列頭部的元素 如果隊列為空,則返回null
put() 添加一個元素 如果隊列滿,則阻塞
take() 移除並返回隊列頭部的元素 如果隊列為空,則阻塞

關於Java隊列更多詳見:java隊列——queue詳細分析


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM