[ACCEPTED]-What is the difference between getFirst() and peekFirst() in Java's LinkedList?-linked-list
Java introduced LinkedList
in version 1.2. This is 6 when the getFirst
method has been provided. This 5 message threw NoSuchElementException
when the list is empty, causing 4 programmers to do an extra check before 3 the call:
Element e = null;
if (!myList.isEmpty()) {
e = myList.getFirst();
}
This was an inconvenience, which 2 has been fixed in Java version 1.6 by adding 1 the peekFirst
method and other methods of the Dequeue<T>
interface.
Only one reson: 1) It reduces the Exception 3 Handling while development
public E peekFirst() {
if (size==0)
return null;
return getFirst();
}
Above is the implementation 2 of peekFirst(), it just check the size ZERO, and 1 returns NULL instead of throwing Exception
LinkedList is a Deque. Deque API defines 4 methods which exist in two forms: one throws 3 an exception if the operation fails, the 2 other returns a special value (either null 1 or false, depending on the operation).
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.