Positional Random access required in a linked list and in an ArrayList

ArrayList Vs LinkedList

1) 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:

  1. Both ArrayList and LinkedList are implementation of List interface.
  2. They both maintain the elements insertion order which means while displaying ArrayList and LinkedList elements the result set would be having the same order in which the elements got inserted into the List.
  3. Both these classes are non-synchronized and can be made synchronized explicitly by usingCollections.synchronizedList method.
  4. The iterator and listIterator returned by these classes are fail-fast (if list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException).

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:

  • ArrayList documentation
  • LinkedList Javadoc

ArrayList Vs LinkedList in Java

ArrayList 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.

  1. Search Operation
  2. Manipulation
  3. Behaviour
  4. Memory Overhead

1. Overview

Collections in Java are based on a couple of core interfaces and more than a dozen implementation classes. The wide selection of different implementations can sometimes lead to confusion.

Deciding on which collection type to use for a particular use case is not a trivial task. That decision can have a great impact on our code readability and performance.

Instead of explaining all types of collections in a single article, we'll explain three of the most common ones: ArrayList, LinkedList, and HashMap. In this tutorial, we'll look at how they store data, their performance, and recommend when to use them.

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:

  • Both implements List interface and they got default behaviour of list interface, i.e., both are ordered collection, and they will maintain insertion order.
  • Both allow inserting null as well as different types of objects.
  • Both implements cloneable interface both the elements themselves are not cloned.
  • Both are not synchronised collections which can be synchronised through using Collections.synchronisedList()method.
  • Iterator and list Iterator methods for both are fail-fast which will throw ConcurrentModificationException whereas fail-safe will not throw that.

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.

Positional Random access required in a linked list and in an ArrayList

Apples and Oranges are different –
Let’s get into the differences between ArrayList and LinkedList.

Applications and Limitations
In an ArrayList, the maximum number of elements in the data structure should be none else
you cannot opt for ArrayList. You can initialise with an initial capacity which protects duplicating
and wrong array allocations. ArrayList is indexed by int. So, it can go up to 32bits. Hence in an
ArrayList, it is not possible to store elements that are more than 2^32.

LinkedList works better even when the addition rate is greater than the read rate. For instance,
let us take a list with a time sequence. You will get numerous answers at each second. In this
type of case, LinkedList is considered a better choice since the addition rate is higher.

  • Implementation: ArrayList is a growable array implementation and implements RandomAccess interface while LinkedList is doubly-linked implementation and does not implement RandomAccess interface. Example: Having a collection of 10 million objects, implementing the RandomAccess interface takes the same time to retrieve the 9th element and 16599th element. This makes ArrayList more powerful. Elements from both LinkedList and ArrayList can be accessed randomly; however, ArrayList’s time complexity is O(1), and LinkedList is O(n).
  • Capacity and Fetching of elements: Initial capacity for Array list is ten which can be changed while in LinkedList there is no initial capacity. ArrayList is useful for fetching elements from the middle of the collection. But it is not suitable for addition or deletion of elements while LinkedList is excellent for adding and deleting elements from the centre of the collection.
  • Memory Consumption: ArrayList consumes less memory than LinkedList as it stores only data of a particular index. In comparison, LinkedList consumes more memory than ArrayList as it holds the address of previous and next object and value of the actual item. ArrayList elements are stored in consecutive memory locations, while LinkedList nodes are stored randomly in memory locations. ArrayList holds real data and its index while LinkedList holds data on each node. Link-list would be better since it doesn’t double in size when the max is reached. Let’s say you have 251 names and then the array doubles to 500 when you get 250. you then allocated 249 different spots in memory for nothing. In the long run, LinkedList is better compared to ArrayList as far as memory goes.
  • Based on Data structure: ArrayList is indexed based data structure where an array index is put to access a particular element. E.g.: [5] where 5 is the index, you can access the element with the help of the index. LinkedList is a reference-based data structure whereby knowing the address only; you can go into a particular location and find the data. ArrayList is a static data structure where elements are allocated during compile time while LinkedList is a dynamic data structure where node position is assigned during run time.
  • Accessing of elements: In ArrayList elements can be directly or randomly accessed while in LinkedList, the elements can be accessed only sequentially. E.g., In ArrayList let us say A6 is given and if you want to go to the third element, you can write A[2], and it directly goes to the third element, but it’s not possible in LinkedList.
  • Speed of operation – Who’s the fastest: Comparing the speed of operation between ArrayList and LinkedList, check with the use of add() get() remove(). Complexity of time in ArrayList can be tested with the usage of get() – O(1) , add() – O(1) , remove() – O(n) and in LinkedList get() – O(n) , add() – O(1) , remove() – O(n). Testing your code with these examples will help you determine the time difference between ArrayList and LinkedList. Observing the test codes, you can be clear that LinkedList is faster in add and remove compared to ArrayList. ArrayList is faster in get(). Elements to be added or removed are too large, go for LinkedList. Usage of get() is more, go for ArrayList. Again, if you don’t have element access in a large number, go for LinkedList.
  • Performance of ArrayList and LinkedList: Both have pros and cons in it. In a LinkedList, adding the elements is unlimited while in an ArrayList, it is restricted to a specific value as it is constrained. It can also be resized but resizing is a bit costly operation, and you can go with LinkedList in this case. Removing the elements in a LinkedList is easy too, but in an ArrayList, eliminating elements will leave empty memory spaces which are wastage in your device. In a LinkedList, the node contains both the data it has and the data to the adjacent node. Hence, LinkedList holds more memory space. LinkedList could be used for large lists of data since the total elements vary accordingly. In an ArrayList, the maximum elements in the list will be known, and it can be used for small lists.
  • Interfaces in the two: In an ArrayList, list interface is implemented by the class. List interface is the inherited interface of the collection. It stores the collection in sequence. It implements the list interface which extends to the collection. In a LinkedList, both list interface and deque interface are implemented by the class. “Double-ended queue” is abbreviated as Deque. Its interface is a branch of queue interface. It supports adding and removing the elements from both ends of the data. Removing/ adding can be done either in a queue or stack. In a queue, the data works in First-in-first-out (FIFO) and a stack, the data fits in last-in-first-out (LIFO). Data adding or data removal is double-ended in Deque. LinkedList and ArrayDeque implement the Deque interface which extends to the queue interface, then to the collection, finally it extends to the iterable interface. ArrayList and LinkedList based on operations performed. If you are using retrieval operations frequently, go for ArrayList. Retrieval operation means collecting the data from a data structure, which can be stored, viewed and printed. ArrayList performs shift operations internally, so the insertion of data in the middle or deletion in the middle is complicated. If you are opting these operations, ArrayList won’t be the best. It stores elements in different memory locations, and hence the process of retrieval will be convenient. If you are performing insertion of data in the middle or deletion of data in the middle is relatively easy, hence go for LinkedList. It works best for frequent addition or deletion in the middle. They do not store elements in different memory locations, and therefore, if you are looking for more Retrieval operations, LinkedList is not the best one. In a retrieval operation, the elements should be stored in consecutive memory locations else it won’t be easy.
  • Applications and Limitations: In an ArrayList, the maximum number of elements in the data structure should be none else you cannot opt for ArrayList. You can initialise with an initial capacity which protects duplicating and wrong array allocations. It is indexed by int. So, it can go up to 32bits. Hence in an ArrayList, it is not possible to store elements that are more than 2^32. LinkedList works better even when the addition rate is greater than the read rate. For instance, let us take a list with a time sequence. You will get numerous answers at each second. In this type of case, LinkedList is considered a better choice since the addition rate is higher.

Conclusion
As you’ve reached the end of this article, we hope you are now familiar with the pros and cons of the two. It is dependent on the usage of the list and your requirement. We have summarised implementation, some of the main applications and limitations to make it easier for you to take the first few steps in mastering these concepts. You decide to choose the better option for your use-case.

To explore more topics to read, click here.