Very Common Java Interview Question : When to use ArrayList and when LinkedList ?
Short is answer is : Use ArrayList for better traversal or search and use LinkedList for better insertions and deletions.
Explanation :
1) Linked List is a Doubly Linked List implementation of List Interface, where as ArrayList is an re sizable Array implementation of List Interface. LinkedList can act as both List and Queue where as ArrayList can only act as List.
2) LinkedList has a reverse iterator which it uses to reach an element from end if the path is shorter.
3) A search operation is faster in ArrayList : it has a complexity of O(1) where as in an LinkedList it is O(n) as you have to iterate over number of records in LinkedLIst.
4) Insertions are faster in LinkedList than ArrayList. In LinkedList we just have to break the nodes and put our entry. But in case of arrayList, there is an overhead of moving the array indexes and then re sizing the array if the size has increased.
4) Deletions are almost the same in ArrayList and Linked List because we have to traverse the node to delete. And in ArrayList they have to update to a new Array.
5) For Manipulation of data use LinkedList and for search operations use ArrayList.
Short is answer is : Use ArrayList for better traversal or search and use LinkedList for better insertions and deletions.
Explanation :
1) Linked List is a Doubly Linked List implementation of List Interface, where as ArrayList is an re sizable Array implementation of List Interface. LinkedList can act as both List and Queue where as ArrayList can only act as List.
2) LinkedList has a reverse iterator which it uses to reach an element from end if the path is shorter.
3) A search operation is faster in ArrayList : it has a complexity of O(1) where as in an LinkedList it is O(n) as you have to iterate over number of records in LinkedLIst.
4) Insertions are faster in LinkedList than ArrayList. In LinkedList we just have to break the nodes and put our entry. But in case of arrayList, there is an overhead of moving the array indexes and then re sizing the array if the size has increased.
4) Deletions are almost the same in ArrayList and Linked List because we have to traverse the node to delete. And in ArrayList they have to update to a new Array.
ArrayList is slower than LinkedList because it has to free up a slot in the middle of the array which means moving some references here and there and in the worst case reallocating the entire array. LinkedList just has to manipulate some references.5) For Manipulation of data use LinkedList and for search operations use ArrayList.
No comments:
Post a Comment