The offerFirst(E e) method of Deque Interface inserts the specified element into the front of the Deque if it is possible to do so immediately without violating capacity restrictions. This method is preferable to addFirst() method since this method does not throws an exception when the capacity of the container is full since it returns false.
boolean offerFirst(E e)
Parameters: This method accepts a mandatory parameter e which is the element to be inserted in the front of the Deque.
Returns: This method returns true on successful insertion else it returns false.
Exceptions: The function throws four exceptions which are described as below:
- ClassCastException: when the class of the element to be entered prevents it from being added to this container.
- IllegalArgumentException: when some property of the element prevents it to be added to the Deque.
- NullPointerException: when the element to be inserted is passed as null and the Deque’s interface does not allow null elements.
Below programs illustrate offerFirst() method of Deque:
The Deque is not full and 10 is inserted The Deque is not full and 15 is inserted The Deque is not full and 25 is inserted The Deque is full Deque: [25, 15, 10]
Exception in thread "main" java.lang.NullPointerException at java.util.concurrent.LinkedBlockingDeque.offerFirst(LinkedBlockingDeque.java:342) at GFG.main(GFG.java:21)
Note: The other two exceptions are internal and are caused depending on the compiler hence it cannot be shown in the code.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.