Yes, this is an old topic, but I still have some confusions.
In Java, people say:
-
ArrayList is faster than LinkedList if I randomly access its elements. I think random access means “give me the nth element”. Why ArrayList is faster?
-
LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList’s slower since the internal backing-up array needs to be reallocated. A code explanation:
List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.remove("b"); System.out.println(list.get(1)); //output "c" -
LinkedList is faster than ArrayList for insertion. What does insertion mean here? If it means to move some elements back and then put the element in the middle empty spot, ArrayList should be slower than LinkedList. If insertion only means an add(Object) operation, how could this be slow?
ArrayListhas direct references to every element in the list, so it can get the n-th element in constant time.LinkedListhas to traverse the list from the beginning to get to the n-th element.ArrayListis slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using theListIterator.remove()API,LinkedListjust has to manipulate a couple of references; if the deletion is done by value or by index,LinkedListhas to potentially scan the entire list first to find the element(s) to be deleted.Yes, this is what it means.
ArrayListis indeed slower thanLinkedListbecause it has to free up a slot in the middle of the array. This involves moving some references around and in the worst case reallocating the entire array.LinkedListjust has to manipulate some references.