![]() |
VOOZH | about |
In Java, the LinkedList class is present in java.util package, and it also has different methods that do the work of flexible addition of elements and help addition both at the front and back of the list. In this article, we cover the LinkedList offer(), offerFirst(), and offerLast() methods. These methods are useful when we want to add an element to a specific position of a LinkedList.
This method is used to add an element to the last or end part of a LinkedList. This method is also used in the queue interface that is internally used in the LinkedList. This method does not throw any exception, unlike the add() method.
Syntax:
public boolean offer(E e)
Example: Adding an element to the LinkedList using the method offer(E e).
The Linked list is : [3, 5, 7]
Explanation: In the above example, we use the offer() method which add the element in the last of a LinkedList.
This method is useful when we want to add the an element in the starting of the LinkedList. Using this method, we can add the element in the first position of the LinkedList and this method is part of Deque interface which allows us to perform operations on both front and back end.
Syntax:
public void offerFirst(E e)
Example: Adding an element in the first position of a LinkedList using offerFirst(E e).
The initial Linked list is : [Geeks, 4, Geeks, 8] LinkedList after insertion using offerFirst() : [Geek1, Geeks, 4, Geeks, 8]
Explanation: In the above example, we use the offerFirst() method to add "Geek1" to the first position of a LinkedList.
This method is used to add an element in the end of the list or we can say it insert the element in the last position in a LinkedList. It is similar to the add() and offer() method which add the element in the last of a LinkedList.
Syntax:
public void offerLast(E e)
Example: Adding an element in the last position using the method offerLast( E e).
The initial Linked list is : [Geeks, 4, Geeks, 8] LinkedList after insertion using offerLast() : [Geeks, 4, Geeks, 8, Geek3]
Explanation: In the above example, we use the offerLast() method which adds "Geek3" to the last position of a LinkedList.
Example: Using the offerFirst() and offerLas() methods of LinkedList to perform practical operation on priority addition in queues where elements having a greater number than threshold.
The initial Linked list is : [12, 4, 8, 10, 3, 15] The prioritized Linked list is : [15, 10, 12, 4, 8, 3]
Explanation: In the above example, we use methods offer(), offerFirst() and offerLast() to perform the operation to add the element on the basis of their priority this is the real life example where we need to use these methods.