It is said that the complexity of the LinkedList remove and the add operation is of O(1)
. and in case of ArrayList
it is of O(n)
.
ArrayList provides resizable-array and stores "references" or "pointers" to actual storage. This array of references has to be recreated if the array is expanded beyond its allocated size. In other words, inserting a node at the beginning would require either all the existing elements to be moved up one, or to re-allocate the whole list if it's beyond it's allocated size. That's why insertion is O(n)
.
A LinkedList consists of a chain of nodes; each node is separated allocated. And so while inserting, it's not necessary to traverse all the nodes. And that's why it has the complexity O(1)
.
However, if you're inserting at end and you have reference of only first node, then you may have to traverse the entire list and thus complexity in this case will be O(n).
EDIT
If you look at the source code of java.util.LinkedList
you can find that LinkedList
always keeps the track of last element
Following are some code snippets from actual java.util.LinkedList
class.
package java.util;
...
public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, java.io.Serializable
{
transient int size = 0;
/**
* Pointer to first node.
*/
transient Node first;
/**
* Pointer to last node.
*/
transient Node last;
...
...
/**
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
linkLast(e);
return true;
}
...
...
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
...
...
}
See particularly the linkLast()
method. It doesn't traverse the entire list. It just inserts the element at the end of the list and that's why time complexity is O(1)
.