Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between poll(),pollFirst(),pollLast(),removeFirst() and remove() methods which are used on a LinkedList object in Java? [closed]

Tags:

java

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.

like image 339
Pamuleti Pullagura Avatar asked Nov 28 '22 14:11

Pamuleti Pullagura


2 Answers

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()

like image 81
Eran Avatar answered Dec 11 '22 04:12

Eran


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.

like image 20
Raman Shrivastava Avatar answered Dec 11 '22 05:12

Raman Shrivastava