What is the difference between ArrayList and LinkedList in collection framework?

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 →


ArrayList vs LinkedList in Java

An 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




// Java program to Illustrate Working of an ArrayList
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList of Integer type
ArrayList<Integer> arrli
= new ArrayList<Integer>();
// Appending the new elements
// at the end of the list
// using add () method via for loops
for (int i = 1; i <= 5; i++)
arrli.add(i);
// Printing the ArrayList
System.out.println(arrli);
// Removing an element at index 3
// from the ArrayList
// using remove() method
arrli.remove(3);
// Printing the ArrayList after
// removing the element
System.out.println(arrli);
}
}
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.

Note: This class implements the LinkedList Data Structure.

Example

Java




// Java program to Demonstrate Working of a LinkedList
// Importing required classes
import java.util.*;
// Main class
class GFG {
// main driver method
public static void main(String args[])
{
// Creating an object of the
// class linked list
LinkedList<String> object
= new LinkedList<String>();
// Adding the elements to the object created
// using add() and addLast() method
// Custom input elements
object.add("A");
object.add("B");
object.addLast("C");
// Print the current LinkedList
System.out.println(object);
// Removing elements from the List object
// using remove() and removeFirst() method
object.remove("B");
object.removeFirst();
System.out.println("Linked list after "
+ "deletion: " + object);
}
}
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

ArrayList LinkedList
This class uses a dynamic array to store the elements in it. With the introduction of generics, this class supports the storage of all types of objects. This class uses a doubly linked list to store the elements in it. Similar to the ArrayList, this class also supports the storage of all types of objects.
Manipulating ArrayList takes more time due to the internal implementation. Whenever we remove an element, internally, the array is traversed and the memory bits are shifted. Manipulating LinkedList takes less time compared to ArrayList because, in a doubly-linked list, there is no concept of shifting the memory bits. The list is traversed and the reference link is changed.
This class implements a List interface. Therefore, this acts as a list. This class implements both the List interface and the Deque interface. Therefore, it can act as a list and a deque.
This class works better when the application demands storing the data and accessing it. This class works better when the application demands manipulation of the stored data.




Article Tags :
Difference Between
Java
Java-ArrayList
Java-Collections
java-LinkedList
java-list
Practice Tags :
Java
Java-Collections
Read Full Article

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.



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 Java

Now 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
  • How to sort a Map by keys and values in Java? (tutorial)
  • Top 10 Courses to learn Java for Beginners (best courses)
  • How to sort an ArrayList in ascending and descending order in Java? (tutorial)
  • 10 Free courses to learn Java in-depth (courses)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • 10 courses to learn Data Structure in-depth (courses)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Top 5 Courses to learn Java Collections and Stream (courses)
  • What is the difference between TreeMap and TreeSet in Java? (answer)
  • The difference between HashSet and TreeSet in Java? (answer)
  • 7 Best Courses to learn Data STructure and Algorithms (best courses)
  • 20+ basic algorithms interview questions for programmers (questions)
  • Top 5 Courses to become full-stack Java developer (courses)
  • The difference between Hashtable and HashMap in Java? (answer)
  • 50+ Core Java Interview Questions and Answers (questions)

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.

Difference Between ArrayListvs LinkedList

ArrayList vs LinkedList both are a part of the collection framework where both are present in java.util package. ArrayList is used to store the homogeneous elements at contiguous memory locations according to the indexes. These indexes can be used to access the elements directly. LinkedList type of collection is used to store any type of elements at any of the available memory locations using nodes. These nodes store the pointer that points to the next node and previous node(in the circular list) and helps in efficient insertion and deletion from the list.

Head to Head Comparison between ArrayListvs LinkedList (Infographics)

Below are the top 12 comparisons between ArrayList vs LinkedList:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
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,378 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 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:

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.

Recommended Articles

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

Video liên quan

Postingan terbaru

LIHAT SEMUA