Home > Software design >  The real differences between pop(), remove() and poll() in LinkedList<E>
The real differences between pop(), remove() and poll() in LinkedList<E>

Time:11-13

I've tried to find some information about differences between pop(), poll() and remove() in LinkedList but unfortunately I didn't find out any precision answer. The only information I have got was that:

-pop() removes first element of the list and throws exception if the list is empty -remove() works the same as pop() -poll() removes first element of the list but if the list is empty return null

And here's my question. Is it true that remove() and pop() have one small difference that I can add an Index to remove method? For example list.remove(3). I see that it is impossible to do with pop()

LinkedList<Integer> list = new LinkedList<>();

list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
```
list.pop(); //Output: 4, 3, 2, 1
//or
list.poll(); //Output: 4, 3, 2, 1
//or
list.remove(3); //Output: 5, 4, 3, 1

CodePudding user response:

Technically, LinkedList has three remove methods. They have the same name, but differ in their parameter lists. Having several methods by the same name, but different parameter lists, is called "overloading".

So, to answer your question: There is no difference between pop() and remove(), but there is a difference between pop() and remove(int index).

This is possible, because remove() and remove(int index) are two different methods. (Technically, remove() and remove(int index) could do totally different things. But that would be very bad practice, because any sensible person expects two methods that share the same name to do similar things.)

The Java API documentation for LinkedList lists all available methods and explains their behavior.

  • Related