What is the difference between ArrayList and LinkedList in C#?

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes.

However, there are many differences between ArrayList and LinkedList classes that are given below.

ArrayListLinkedList
1) ArrayList internally uses a dynamic array to store the elements.LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.LinkedList is better for manipulating data.

Example of ArrayList and LinkedList in Java

Let's see a simple example where we are using ArrayList and LinkedList both.

Test it Now

Output:

arraylist: [Ravi,Vijay,Ravi,Ajay] linkedlist: [James,Serena,Swati,Junaid]
Next TopicListIterator in Java Collection


← prev next →


LinkedList internal implementation explained

LinkedList 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 explained

For 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:

  • Twitter
  • Facebook

Like this:

Like Loading...

Related

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 –

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

What is the difference between ArrayList and LinkedList in C#?

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 LinkedList

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

What is the difference between ArrayList and LinkedList in C#?

Key differences between ArrayListvs LinkedList

Let 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
What is the difference between ArrayList and LinkedList in C#?
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.

What is the difference between ArrayList and LinkedList in C#?

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:

What is the difference between ArrayList and LinkedList in C#?

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 LinkedList

The table below summarizes the comparisons between ArrayList vs LinkedList:

ArrayListLinkedList
ArrayList is a class in a collection framework that uses a dynamic array to store its elements.LinkedList class of collection framework uses doublyLinkedListto store the elements.
Insertion operation performed is slow as each insertion made at an index requires a shift of the latter element in the list by expanding the array-size and copy the elements to the new indexes, thus have time complexity O(n).Insertion operation is fast as only next and previous pointerupdationis required, thus have complexityO(1).
It can only be used to implement the list since it implements only the List interface.It can be used to implement List as well as queue since it implements List and the Deque interface.
Data access and storage is very efficient since it stores the elements according to the indexes.Since each data access requires a complete traversal of the list thus is comparatively slow.
Deletion operation is also not very efficient because it also requires resizing the array and copying elements, thus having time complexity O(n).Deletion operation is more efficient comparatively since it requires the only updation of pointers of the previous and next node, thus have complexity O(1).
ArrayListcan be used to store similar types of data.Any type of data can be stored usingLinkedList.
ArrayList stores the elements according to the indexes; thus, less memory overhead is involved.LinkedList involves more memory overhead since
Memory for theArrayListis allocated at compile time only.Thusit is known as Static Memory Allocation.Memory is allocated to the LinkedList during run-time, thus known as dynamic memory allocation.
ArrayListcan be one dimensional, two-dimensional or multi-dimensional.LinkedListcan be either singlyLinkedList, doublyor circularLinkedList.
Memory to the ArrayList is allocated at the Stack memory location.Memory to the LinkedList is allocated in the heap memory section.
The size of ArrayList needs to be declared before execution.The size of the LinkedList is variable thus need not be declared.
Inefficient memory utilization.Good memory utilization.

Examples of ArrayList and LinkedList

Code:

packageTry;
importjava.util.ArrayList;
importjava.util.LinkedList;
publicclassOffice
{
publicstaticvoidmain(String[]args)
{
ArrayList<String> arr1 =newArrayList<String>();
arr1.add("0.Static Memory Allocation");
arr1.add("1.Faster element access");
arr1.add("2.Inefficient insertion/deletion");
System.out.println("ArrayListobjectproperties :" + arr1);
if(arr1.contains("1.Fasterelement access"))
System.out.println("Present");
else
System.out.println("Not Present");
LinkedList<String> linklist1 =newLinkedList();
linklist1.add("0.Dynamuc Memory Allocation");
linklist1.add("1.Slower element access");
linklist1.add("2.Faster insertion/deletion");
System.out.println("LinkedList objectProperties :" + linklist1);
if(linklist1.contains("1.Slowerelement access"))
System.out.println("Present");
else
System.out.println("Not Present");
}
}

Output:

What is the difference between ArrayList and LinkedList in C#?

Conclusion

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

This 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 –

  1. JPanel in Java
  2. Array vs ArrayList
  3. Java Vector vs ArrayList
  4. LinkedList in Java

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

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.

What is the difference between ArrayList and LinkedList in C#?

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.