I have a LinkedList object.
I want to apply these 5 methods on my LinkedList object.
LinkedList<String> ll = new LinkedList<String>();
1) Object o = ll.poll();
2) Object o = ll.pollFirst();
3) Object o = ll.pollLast();
4) ll.remove();
5) Object o = ll.removeFirst();
When I use poll(),pollFirst(),removeFirst() those are removing the first item of the list.
Any one can tell me what happened when I use these methods on my LinkedList object? and what are the differences between these 5 methods those are applicable on a LinkedList object.
Thanks in advance.
The Javadoc tells you :
poll() : Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
remove() : Return the head of this list, throws NoSuchElementException if this list is empty
pollFirst() is the same as poll().
pollLast() return the last element of this list, or null if this list is empty
removeFirst() is the same as remove()
I think the naming of the methods is quite obvious telling what do they do.
Only bit confusing thing is why 2 methods doing same thing in poll() and pollFirst(). For that see below -
LinkedList implements two interfaces - Queue and Deque. And Deque extends from Queue. Now, Deque has defined the method - Deque#pollFirst() and inherited the method - Queue#poll(). So, LinkedList has basically these two methods defined for the two interfaces it implements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With