Difference between ArrayList and LinkedListArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes. Show
However, there are many differences between ArrayList and LinkedList classes that are given below.
Example of ArrayList and LinkedList in JavaLet's see a simple example where we are using ArrayList and LinkedList both. Test it NowOutput: arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
Next TopicListIterator in Java Collection ← prev next → ArrayList vs LinkedList in JavaAn array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to solve this problem named ArrayList and LinkedList is discussed. ArrayList is a part of the collection framework. It is present in the java.util package and provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. We can dynamically add and remove items. It automatically resizes itself. The following is an example to demonstrate the implementation of the ArrayList. Example Java
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] LinkedList is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. The following is an example to demonstrate the implementation of the LinkedList.
Example Java
Output:
[A, B, C]
Linked list after deletion: [C]
Now after having an adequate understanding of both of them let us do discuss the differences between ArrayList and LinkedList in Java
Article Tags :
Difference Between Java
Java-ArrayList Java-Collections java-LinkedList java-list Practice Tags :
Java Java-Collections 1. OverviewWhen it comes to collections, the Java standard library provides plenty of options to choose from. Among those options are two famousListimplementations known asArrayListandLinkedList,each with their own properties and use-cases. In this tutorial, we're going to see how these two are actually implemented. Then, we'll evaluate different applications for each one. ArrayList Vs LinkedList1) Search: ArrayList search operation is pretty fast compared to the LinkedList search operation.get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n). Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element. 2) Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element) and O(1) in best case (While removing last element). Conclusion: LinkedList element deletion is faster compared to ArrayList. Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list. Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element. 3) Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. Reason is same as explained for remove. 4) Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively. There are fewsimilarities betweenthese classes which are as follows:
When to use LinkedList and when to use ArrayList?1) As explained above the insert and remove operations give good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Hence if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice. 2) Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet. References:
What is ArrayList?ArrayList is the simplest list that can store different types of data. To understand ArrayList, consider the following data stored in an array – names[0] = "Mac"; names[1] = "Jony"; names[2] = "Mary"; names[3] = "Donald"; names[4] = "Phoebe"; where Student is a class that holds information about students of a college like a name, age, subject, average marks, email id, gender, and whether they have distinguishing marks or not. Details of each Student are stored in an array, names. The array size is fixed as 5. However, what happens if there are more students than 5? With ArrayList, this problem will not occur. ArrayList is a dynamic array, which grows in size as the number of elements increases. ArrayList namesList = new ArrayList();namesList.add("Mac"); namesList.add("Jony"); namesList.add("Mary"); namesList.add("Donald"); namesList.add("Phoebe"); As we see, there is no initial size given to the list. It can just add elements as the list grows. In fact, any type of manipulation is easy with ArrayList. If you want to access any element of the list, you can easily get it using the index. The first index is always zero. Suppose, you want to replace the name “Mary” to “Maryln”, you could do the following – namesList.remove(namesList.get(2));namesList.add(2, "Maryln"); We have removed the previous name and added the new one in the same place. You can also add elements at any location. For example, namesList.add(2, "Joseph");This will not replace ‘Maryln’ but will move it to the next index. If you print the list you will get – [Mac, Jony, Joseph, Maryln, Donald, Phoebe]0 1 2 3 4 5 This means to accommodate ‘Joseph’, all the other elements have been shifted to the right. Same way, when we removed Mary, all the other elements had to be moved to the left. Duplicate values are perfectly acceptable in ArrayList. If we add another element with the same name, the list size will grow and the value will be displayed without any issue. ArrayList implements the List interface which in turn extends the interface Collection. The collection is extended by the Iterable interface. The hierarchy of ArrayList is as follows Source: Javadocs It is also easy to sort objects in ascending or descending order with ArrayList using the method sort of the Java .util.Collections class. ArrayList is not synchronized, which means if multiple threads change a list at the same time, the result could be unpredictable. We can also add a value of null to an ArrayList, which will be displayed at its position as “null”. One of the most famous interview questions for beginners as well as Java developers with two-three years of experience is the difference between ArrayList and LinkedList.Before getting into differences, let’s understand the similarities between ArrayList and LinkedList so that it will not be challenging to know the differences. Some of the similarities are as follows:
Now let’s have a brief introduction about “What is ArrayList?” and “What is LinkedList?” ArrayList is a growable array which has an initial capacity of ten. After reaching its maximum capacity, a new ArrayList is created with increased capacity, and all the records will be copied in the new ArrayList. The formula for new ArrayList’s capacity is New Capacity = Current capacity*1.5+1 ArrayList can be created with the required initial capacity. Since ArrayList implements a random access interface, it is good to use when its elements are fetched frequently. ArrayList is not good to use for frequent addition and deletion of elements due to multiple shift operations. LinkedList internally maintains doubly-linked lists which store the memory address of previous and next object, so there will be no kind of structure which will keep memory address of the previous node and next node. There is no initial capacity defined for LinkedList, and it is not implementing a RandomAccess interface. LinkedList is faster than ArrayList while inserting and deleting elements, but it is slow while fetching each element. Apples and Oranges are different – Applications and Limitations LinkedList works better even when the addition rate is greater than the read rate. For instance,
Conclusion To explore more topics to read, click here. When to use ArrayList vs LinkedList in JavaBefore comparing differences between ArrayList and LinkedList, let's see What is common between ArrayList and LinkedList in Java :1) Both ArrayList and LinkedList are an implementation of the List interface, which means you can pass either ArrayList or LinkedList if a method accepts the java.util.List interface. Btw, if you are new to Java's collections framework then I suggest you first go throughJava Fundamentals: Collectionsby Richart Warburton. It's an online Java course on Pluralsight, which you can avail of free by signing their 10-day free trial. IMHO, it's worth going through that course to learn Java collections in the right way. 2) Both ArrayList and LinkedList are not synchronized, which means you can not share them between multiple threads without external synchronization. See here to know How to make ArrayList synchronized in Java. 3) ArrayList and LinkedList are ordered collection e.g. they maintain insertion order of elements i.e. the first element will be added to the first position. 4) ArrayList and LinkedList also allow duplicates and null, unlike any other List implementation e.g. Vector. 5) An iterator of both LinkedList and ArrayList are fail-fast which means they will throw ConcurrentModificationException if a collection is modified structurally once the Iterator is created. They are different than CopyOnWriteArrayList whose Iterator is fail-safe. Difference between LinkedList and ArrayList in JavaNow let's see some differences between ArrayList and LinkedList and when to use ArrayList and LinkedList in Java.1. Underlying Data Structure The first difference between ArrayList and LinkedList comes with the fact that ArrayList is backed by Array while LinkedList is backed by LinkedList. This will lead to further differences in performance. 2. LinkedList implements Deque Another difference between ArrayList and LinkedList is that apart from the List interface, LinkedList also implements theDeque interface, which provides first in first out operations for add() and poll() and several other Deque functions. Also, LinkedList is implemented as a doubly-linked list and for index-based operation, navigation can happen from either end (seeComplete Java MasterClass). 3. Adding elements in ArrayList Adding an element in ArrayList is O(1) operation if it doesn't trigger re-size of Array, in which case it becomes O(log(n)), On the other hand, appending an element in LinkedList is O(1) operation, as it doesn't require any navigation. 4. Removing an element from a position In order to remove an element from a particular index e.g. by calling remove(index), ArrayList performs a copy operation which makes it close to O(n) while LinkedList needs to traverse to that point which also makes it O(n/2), as it can traverse from either direction based upon proximity. 5. Iterating over ArrayList or LinkedList Iteration is the O(n) operation for both LinkedList and ArrayList where n is a number of an element. 6. Retrieving element from a position The get(index) operation is O(1) in ArrayList while its O(n/2) in LinkedList, as it needs to traverse till that entry. Though, in Big O notation O(n/2) is just O(n) because we ignore constants there. If you want to learn more about how to calculate time and space complexity for your algorithms using Big O notation, I recommend reading Grokking Algorithms by Aditya Bhargava, one of the most interestingbooks on this topic I have read ever. 7. Memory LinkedList uses a wrapper object, Entry, which is a static nested class for storing data and two nodes next and previous while ArrayList just stores data in Array. So memory requirement seems less in the case of ArrayList than LinkedList except for the case where Array performs the re-size operation when it copies content from one Array to another. If Array is large enough it may take a lot of memory at that point and trigger Garbage collection, which can slow response time. From all the above differences between ArrayList vs LinkedList, It looks like ArrayList is the better choice than LinkedList in almost all cases, except when you do a frequent add() operation than remove(), or get(). It's easier to modify a linked list than ArrayList, especially if you are adding or removing elements from start or end because the linked list internally keeps references of those positions and they are accessible in O(1) time. In other words, you don't need to traverse through the linked list to reach the position where you want to add elements, in that case, addition becomes an O(n) operation. For example, inserting or deleting an element in the middle of a linked list. In my opinion, use ArrayList over LinkedList for most of the practical purposes in Java. Further Learning Java In-Depth: Become a Complete Java Engineer Collection in Java - Educative Algorithms and Data Structures - Part 1 and 2 Other Java Collection Articles you may like
Thanks for reading this article so far, if you like this article then please share it with your friends and colleagues. If you have any questions or doubts then please drop a note. P. S. -If you are keen to learn Java Programming in-depth but looking for free online courses then you can also check outJava Tutorial for Complete Beginners (FREE)course on Udemy. It's completely free and you just need an Udemy account to join this course. |