anonymous anonymous - 1 month ago 7
Java Question

ArrayList, LinkedList and Vector which one is the best for adding or removing the element from the list

I appeared for an interview where interviewer asked me about ArrayList, Linked list and Vector. His question was

ArrayList, LinkedList, and Vector
are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list ? And I was supposed to answer including any other alternatives I may be aware of.

I answered him but he seems little not impressed by my answer.

Can someone tell me more about this ?

Thank you

Answer

There is a better explanation for this question here:
When to use LinkedList over ArrayList?

Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove http://trove.starlight-systems.com/ or HPPC http://labs.carrotsearch.com/hppc.html.