[英]What are the differences between these methods to access other classes in Java?
[英]What is the differences between methods in Java Queue interface ?
在這里檢查Java中的Queue接口
我對方法定義感到困惑:
element()獲取但不移除此隊列的頭部。
就好像
peek()獲取但不移除此隊列的頭部,如果此隊列為空,則返回null。
我可以看到,如果隊列為空,則peek返回null,但實際上兩者都被定義為
拋出:NoSuchElementException - 如果此隊列為空
同樣適用於remove()
和peek()
;
這背后有任何目標,還是只是一個設計陷阱?
讓我們用一個應該回答你問題的表來澄清事情:
+---------+---------------------------+------------------------+
| method | action | throws when not found? |
+---------+---------------------------+------------------------+
| peek | Retrieves, doesn't remove | NO |
| remove | Retrieves, removes | YES |
| element | Retrieves, doesn't remove | YES |
+---------+---------------------------+------------------------+
當沒有找到元素時,有些方法返回null
,其他方法拋出異常。
是檢索和不刪除的方法,其他檢索和刪除的方法。
解釋是在java API for interface Queue: here 。 簡而言之,如果隊列為空,則element()發生異常,並且peek()返回一個特殊值以指示Queue為空
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.