![](/img/trans.png)
[英]What's the difference between the element() and getFirst() methods in the LinkedList class?
[英]What is the difference between getFirst() and peekFirst() in Java's LinkedList?
在Java的LinkedList實現中,我看到兩種方法在我看來具有相同的功能。
getFirst()
返回此列表中的第一個元素。
peekFirst()
檢索但不刪除此列表的第一個元素,如果此列表為空,則返回null。
它們都獲得指向LinkedList中First元素的指針,而不對其進行任何更改。 然后,有什么區別?
我看到的唯一區別是,如果列表為空, peekFirst
返回null
如果列表為空,則getFirst
拋出NoSuchElementException
。 這種設計模式有什么用?
Java在版本1.2中引入了LinkedList
。 這是在提供getFirst
方法的時候。 當列表為空時,此消息拋出NoSuchElementException
,導致程序員在調用之前進行額外檢查:
Element e = null;
if (!myList.isEmpty()) {
e = myList.getFirst();
}
這是一個不便之處,已經在Java版本1.6中通過添加peekFirst
方法和Dequeue<T>
接口的其他方法來修復。
只有一個共鳴:1)它減少了開發時的異常處理
public E peekFirst() {
if (size==0)
return null;
return getFirst();
}
上面是peekFirst()的實現,它只檢查大小ZERO,並返回NULL而不是拋出異常
LinkedList是Deque。 Deque API定義了以兩種形式存在的方法:一種在操作失敗時拋出異常,另一種返回特殊值(null或false,具體取決於操作)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.