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 → LinkedList internal implementation explainedLinkedList resides in programming heap. Why? Because it consist of only on objects and their linkages. As C# LinkedList class is using doubly linked list, each node has two pointers, next and prev, and an item field to hold an item. The pointers help to traverse back and forth easily you traversal can be started form any end. The item field is of generic type as it has to take value of any datatype. Microsoft uses its generic namespace for this purpose. For other languages Union can be used (See PHP internal implementation that how they uses union to accept any value in PHP variables). To access LinkedList, only a pointer to the head is required but we are talking about doubly linkedList and for the ease of traversal, two pointers have been maintained on programming stack, head and tail, to access LinkedList from any end. ArrayList internal implementation explainedFor developer, whatever is going on behind is transparent. We use ArrayList as an infinite space and add and delete elements as we want. But is it really infinite? ArrayList uses an array internally private Object[] _items; The internal implementation of ArrayList can be found on in Microsoft resource reference How they make it infinite?It is achieved by using careful resizing technique. Microsoft put default size to 4 means when you create ArrayList object, an array with length four is created. You can set initial Capacity but using Capacity property. But when underline array filled, then for addition of new element, ArrayList create a new array with double the length of under-use array, copy all elements to new array and add new element, destroy the old one. This copying is done in O(n). This is the overhead that you can reduce by defining capacity carefully. But when underline array filled, then for addition of new element, ArrayList create a new array with double the length of under-use array, copy all elements to new array and add new element, destroy the old one. This copying is done in O(n). This is the overhead that you can reduce by defining capacity carefully. Following is the code for capacity property which resize array if needed // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public virtual int Capacity { get { Contract.Ensures(Contract.Result<int>() >= Count); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } Contract.Ensures(Capacity >= 0); Contract.EndContractBlock(); // We don't want to update the version number when we change the capacity. // Some existing applications have dependency on this. if (value != _items.Length) { if (value > 0) { Object[] newItems = new Object[value]; if (_size > 0) { Array.Copy(_items, 0, newItems, 0, _size); } _items = newItems; } else { _items = new Object[_defaultCapacity]; } } } }If estimated count of items are knows, capacity can be define accordingly to eliminate data copying. What underline array contain?An ArrayList only contain references to the objects, not the objects themselves. All references are the same size, so the problem doesn’t exist. The internal type of the reference is object. If you put a value type in an ArrayList it will be boxed into an object and the reference to that object is stored in the ArrayList. For arrays of reference types, the array stores the references (pointers) to the actual objects, which live in the heap. What is memory performance?Another question could be what about waste of memory allocation. Let say you have 65 elements, you have added 64 but when you add 65th then underline array doubled to 128 and 64 items copied and 65th item added. But now you have wasted 63 array elements. And as each element in ArrayList is a reference so it takes 4 bytes on x86 and 8 bytes on x64 so in this case 252(x86) bytes or 504(x64) bytes wasted. But modern operating systems take care for their memory management. They use many techniques and algorithms to use unused space in a way that this usage becomes transparent to programming language. This technique reduces memory wastage and overhead. Share this:Like this:Like Loading... RelatedWhat 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 – String[] names = new String[5];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”. ArrayList vs LinkedListThe main difference between ArrayList and LinkedList is that ArrayList falls under the category of collection framework of dynamic arrays distinct to standard arrays whereas LinkedList exercises LinkedList Data Structure within its class with variations in every element embraced with a data and address wedge. Key differences between ArrayListvs LinkedListLet us discuss some key differences between ArrayListvs LinkedList in the following points: 1. Type of Elements: ArrayList is used to store homogeneous elements, but LinkedList can be used to store heterogeneous elements also. 2. Insertion: Insertion operation comprises of the addition of an element in the existing list. In the case of ArrayList, when one element needs to be added at the particular index of the list, it is comprised of 2 methods- expansion of the array size with a new size and copying the elements to the newer array at an updated location. The time complexity of this is O(n). In the case of LinkedList, insertion operation is more efficient as memory is variable and allocated dynamically, and no shifting of the element is required; instead, only pointers need to be updated. Thus time complexity is O(1) for insertion operation. Popular Course in this category JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes)39 Online Courses | 23 Hands-on Projects | 225+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions 4.5 (8,365 ratings) Course Price View Course Related Courses Java Training (40 Courses, 29 Projects, 4 Quizzes)Python Training Program (39 Courses, 13+ Projects)HTML Training (12 Courses, 19+ Projects, 4 Quizzes)Thus in case insertion or deletion operation needs to be performed often thus one must choose LinkedList. 3. Data Access: In case one needs to access an element at a location, ArrayList is more efficient in this case since it uses indexes to store the elements and can be easily accessed using the particular index. Whereas in the case of LinkedList needs to traverse the complete list to access the element. Example: Accessing the fourth element in ArrayList A, we just need to mention A[3] as the index in case of an array starts with 0. 4. Deletion: In the case of Deletion also, ArrayList takes more time since it needs to copy the elements to the new array at updated locations thus have time complexity of O(n). In case we use LinkedList, deletion can be performed with O(1) of time complexity as the memory of the node needs to deallocated and pointers of the previous and next node needs to update only. Thus it is more efficient in this case. 5. Memory Allocation: Memory to ArrayList is allocated at the compile time itself; thus, it is compulsory to specify the size of the list before execution. This is known as Static memory allocation. Also, the memory allocated is contiguous. Example: Consider below ArrayList A and the memory address of its elements. Whereas in the case of LinkedList, memory is allocated run time, also known as dynamic memory allocation. Also, the memory location where the elements in LinkedList need not be contiguous. Example: Thusit is easier to expand the size of the list in caseLinkedListthanArrayList. 6. Memory Storage Type: Since memory is allocated to the ArrayList at the compile-time; thus, Stack memory is used. Whereas in the case of LinkedList, memory is allocated from heap memory that is used to allocate memory to the variables at run time. Comparison Table of ArrayListvs LinkedListThe table below summarizes the comparisons between ArrayList vs LinkedList:
Examples of ArrayList and LinkedListCode: packageTry; Output: ConclusionSize of ArrayList needs to be declared at compile time and uses stack memory; thus, insertion and deletion operation inefficient than LinkedList, where memory is allocated in a heap at run time. But since indexes are used thus, data access works faster in ArrayList. Search operation works similarly in both cases. Thus, any of these depends on our needs that which operation will be performed more often. Recommended ArticlesThis is a guide to ArrayList vs LinkedList. Here we discuss the ArrayList vs LinkedList key differences with infographics and comparison table. You may also have a look at the following articles to learn more –
JavaScript Training Program (39 Courses, 23 Projects) 39 Online Courses 23 Hands-on Projects 225+ Hours Verifiable Certificate of Completion Lifetime Access 4 Quizzes with Solutions Learn More 0 Shares Share Tweet Share ArrayList Vs LinkedList in JavaArrayList and LinkedList are the Collection classes , and both of them implements the List interface. LinkedList implements it with a doubly-linked list while ArrayList implements it with a dynamically re-sizing array.
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. |