The Wayback Machine - https://web.archive.org/web/20240927174410/https://www.geeksforgeeks.org/arraylist-vs-linkedlist-java/
Open In App

ArrayList vs LinkedList in Java

Last Updated : 24 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Java Collections Framework Hierarchy

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
1. 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.
2. 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.
3. Inefficient memory utilization. Good memory utilization.
4. It can be one, two or multi-dimensional. It can either be single, double or circular LinkedList.
5. Insertion operation is slow. Insertion operation is fast.
6. 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.
7. 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.
8. Data access and storage is very efficient as it stores the elements according to the indexes. Data access and storage is slow in LinkedList.
9. Deletion operation is not very efficient. Deletion operation is very efficient.
10. It is used to store only similar types of data. It is used to store any types of data.
11. Less memory is used. More memory is used.
12. This is known as static memory allocation. This is known as dynamic memory allocation.

ArrayList is an implementation of the List interface that uses an array to store its elements. It has a fast indexed access time, which means that retrieving elements from an ArrayList by an index is very quick. 

For example, the following code demonstrates how to retrieve an element from an ArrayList:

Java




import java.io.*;
import java.util.ArrayList;
 
class GFG {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        int thirdNumber = numbers.get(2);
        System.out.println("The third number is: " + thirdNumber);
    }
}


Output

The third number is: 3

In addition, inserting or deleting elements from the middle of an ArrayList can be slow, as the entire array needs to be shifted in memory to make room for the new element or to close the gap left by the deleted element.

For example, the following code demonstrates how to insert an element in the middle of an ArrayList:

Java




import java.io.*;
import java.util.ArrayList;
 
class GFG {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(2, 4);
        System.out.println("The numbers are: " + numbers);
    }
}


Output

The numbers are: [1, 2, 4, 3]

LinkedList, on the other hand, is an implementation of the List interface that uses a linked list data structure to store its elements. 

Unlike an ArrayList, a LinkedList does not use an array to store its elements. Instead, each element in a LinkedList is represented by a node that contains a reference to the data stored in the node and a reference to the next node in the list.



Similar Reads

Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
ArrayList and LinkedList remove() methods in Java with Examples
List interface in Java (which is implemented by ArrayList and LinkedList) provides two versions of remove method. boolean remove(Object obj) : It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present. Removes the first occurrence of the specified element from
3 min read
Difference between ArrayList, LinkedList and Vector
ArrayList:Array List is an implemented class of List interface which is present in package java.util. Array List is created on the basis of the growable or resizable array. And Array List is an index-based data structure. In ArrayList, the element is stored in a contiguous location. It can store different data types. And random access is allowed. W
11 min read
Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
Linked list class offers the functionality to "look into" the first and last elements of the list and hence can be useful in cases where only the retrieval is required and not necessarily the deletion is required. Three functionalities are present and all are discussed in this article. 1. peek() : This method retrieves, but does not remove, the hea
4 min read
Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
Linked list also has a function that does the work of flexible addition of elements and helps addition both at front and back of the list, these functions literally "offer" the facility and named offer(). Three types are available and are discussed in this very article below. 1. offer(E e) : This method adds the specified element as the tail (last
4 min read
Java.util.LinkedList.indexOf(), lastIndexof() in Java
Linked list library also offers to depict the first and last index of element that has to be found using the indexOf() and lastIndexOf() functions respectively. They offer a variety as the direct access is not available in the conventionally made linked list, hence knowledge of it is useful. 1. indexOf(Object o) : This method returns the index of t
4 min read
Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
Java's Linked list class offers a function that allows a "Queue Based" working called poll(). This function not only returns deletes the first element, but also displays them while being deleted and hence can have a lot of usage in daily life problems and competitive programming as well. There are 3 variants of poll(), all three are discussed in th
4 min read
Java.util.LinkedList.get(), getFirst(), getLast() in Java
In Java, the LinkedList class provides several methods for accessing the elements in the list. Here are the methods for getting the elements of a LinkedList: get(int index): This method returns the element at the specified position in the LinkedList. The index parameter is zero-based, so the first element has an index of 0.getFirst(): This method r
5 min read
LinkedList removeFirst() Method in Java
In Java, the LinkedList class provides the removeFirst() method to remove and return the first element of the list. If the list is empty, the method throws a NoSuchElementException. Sure, here is an example of using the removeFirst() method in Java, with the full code and output: Java Code import java.util.LinkedList; public class Example { public
3 min read
LinkedList add() Method in Java With Examples
LinkedList is a class implementation of the LinkedList data structure which 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. As we all know that class contains various methods so do here we will be discussing and implementing add() method t
3 min read
LinkedList getFirst() Method in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which 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 Java.util.LinkedList.getFirst() meth
2 min read
LinkedList getLast() Method in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which 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. The Java.util.LinkedList.getLast() method is used to
2 min read
LinkedList clear() Method in Java
The Java.util.LinkedList.clear() method is used to remove all the elements from a linked list. Using the clear() method only clears all the element from the list and not deletes the list. In other words we can say that the clear() method is used to only empty an existing LinkedList. Syntax: void clear() Parameters: This function does not accept any
1 min read
LinkedList addFirst() Method in Java
The java.util.LinkedList.addFirst() method in Java is used to insert a specific element at the beginning of a LinkedList. Syntax: void addFirst(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list. Return Value: This me
1 min read
LinkedList addLast() Method in Java
The java.util.LinkedList.addLast() method in Java is used to insert a specific element at the end of a LinkedList.Syntax: void addLast(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at end of the list.Return Value: This method does not re
1 min read
LinkedList addAll() Method in Java
java.util.LinkedList.addAll(Collection C): This method is used to append all of the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of ArrayList. It is the collectio
3 min read
LinkedList set() Method in Java
The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: LinkedList.set(int index, Object element)Parameters: T
3 min read
LinkedList remove() Method in Java
LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only. Illustration:
4 min read
LinkedList removeLast() Method in Java
In Java, the LinkedList class provides the removeLast() method to remove and return the last element of the list. If the list is empty, the method throws a NoSuchElementException. Example: Java Code import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>();
2 min read
LinkedList get() Method in Java
The Java.util.LinkedList.get() method is used to fetch or retrieve an element at a specific index from a LinkedList. Syntax: LinkedList.get(int index) Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList. Return Value: The method returns the element present at
1 min read
LinkedList size() Method in Java
The Java.util.LinkedList.size() method is used to get the size of the Linked list or the number of elements present in the linked list. Syntax: LinkedList.size()Parameters: This method does not take any parameter. Return Value: This method returns the size or the number of elements present in the LinkedList. Below program illustrates the Java.util.
2 min read
LinkedList indexOf() method in Java
The Java.util.LinkedList.indexOf(Object element) method is used to check and find the occurrence of a particular element in the list. If the element is present then the index of the first occurrence of the element is returned otherwise -1 is returned if the list does not contain the element. Syntax: LinkedList.indexOf(Object element) Parameters: Th
2 min read
LinkedList lastIndexOf() Method in Java with Examples
The lastIndexOf(Object element) method of LinkedList class present inside java.util package is used to check and find the occurrence of a particular element in the list. If the element is present in the list then the lastIndexOf() method returns the index of the last occurrence of the element otherwise it returns -1. This method is used to find the
2 min read
LinkedList contains() Method in Java
The Java.util.LinkedList.contains() method is used to check whether an element is present in a LinkedList or not. It takes the element as a parameter and returns True if the element is present in the list. Syntax: LinkedList.contains(Object element) Parameters: The parameter element is of type LinkedList. This parameter refers to the element whose
2 min read
LinkedList clone() Method in Java
The Java.util.LinkedList.clone() method is used to create a shallow copy of the mentioned linked list. It just creates a copy of the list. Syntax: LinkedList.clone() Parameters: This method does not take any parameters. Return Value: This function returns a copy of the instance of Linked list. Below program illustrate the Java.util.LinkedList.clone
1 min read
LinkedList listIterator() Method in Java
The Java.util.LinkedList.listIterator() method is used to return a list-iterator containing the same elements as that of the LinkedList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method. Syntax: ListIterator new_list = LinkedList.listIterator(int index); Parameters: The param
1 min read
LinkedList pop() Method in Java
The java.util.LinkedList.pop() method is used to remove and return the top element from the stack represented by the LinkedList. The method simply pops out an element present at the top of the stack. This method is similar to removeFirst method in LinkedList. Syntax: LinkedListObject.pop() Parameters: The method does not take any parameter. Return
2 min read
LinkedList removeFirstOccurrence() Method in Java
The java.util.LinkedList.removeFirstOccurrence() is used to remove the first occurrence of the specified element from the list. If there is no occurrence of the specified element the list remains unchanged. Syntax: LinkedListObject.removeFirstOccurrence(Object element) Parameters: The method takes one parameter element which is to be removed from t
2 min read
Reverse a LinkedList in Java
Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below: 1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a p
7 min read
LinkedList spliterator() method in Java
The spliterator() method of LinkedList returns a Spliterator which is late-binding and fail-fast with the same elements as LinkedList. A late-binding Spliterator binds to the source of elements means LinkedList at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can
3 min read