Reputation:
In Java's LinkedList implementation, I see two methods which seems to me like having identical functions.
getFirst()
--Returns the first element in this list.
peekFirst()
--Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
Both of them get the pointer to the First element in the LinkedList without making any changes to it. Then, what's the difference ?
The only difference I see is that peekFirst
returns null
if the list is empty and getFirst
throws a NoSuchElementException
if the list is empty. What was the use of such a design pattern ?
Upvotes: 18
Views: 12899
Reputation: 21
If your LinkedList
has data then there is no difference, but if your LinkedList
is empty then the peekFirst()
method returns null. It doesn't throw any errors or exceptions but getFirst()
method throws an exception if the list is empty.
Upvotes: 0
Reputation: 136162
LinkedList is a Deque. Deque API defines methods which exist in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation).
Upvotes: 3
Reputation: 1035
Only one reson: 1) It reduces the Exception Handling while development
public E peekFirst() {
if (size==0)
return null;
return getFirst();
}
Above is the implementation of peekFirst(), it just check the size ZERO, and returns NULL instead of throwing Exception
Upvotes: 8
Reputation: 727137
Java introduced LinkedList
in version 1.2. This is when the getFirst
method has been provided. This message threw NoSuchElementException
when the list is empty, causing programmers to do an extra check before the call:
Element e = null;
if (!myList.isEmpty()) {
e = myList.getFirst();
}
This was an inconvenience, which has been fixed in Java version 1.6 by adding the peekFirst
method and other methods of the Dequeue<T>
interface.
Upvotes: 20