Difference between LinkedList vs ArrayList

Published April 11, 2022

If you're new to Java programming, you might wonder whether to use a linked list or an ArrayList when working with collections. Both collections perform similar functions, so deciding which one to use can be confusing.

This article outlines the differences between the two and discusses where and when to use each. 

 

Difference between ArrayLists and LinkedList in Java

Based on the following criteria, we will compare an ArrayList and a Linked List:

Manipulation

In both cases, there is a variation in the speed with which arrays are manipulated. ArrayLists are slower in array manipulation than linkedLists. This is because LinkedList is node-based and does not require much bit shifting.

Access

ArrayLists are quicker in storing and retrieving data. This differs from LinkedList which on the other hand supports faster data manipulation.

Implementation

An array list only implements a list, while LinkedList implements both a list and a queue. LinkedList is often used as queues as well.

 

Internal Implementation

In ArrayLists, elements are stored in a dynamic array, whereas linked lists use a doubly-linked list.

 

When to use an array list or linked list?

ArrayLists are appropriate when working with a read-only collection, while LinkedList is appropriate when working on a collection that allows for various data modifications, such as addition and deletion.

Example

Example of a Linked List

import java.util.LinkedList;

import java.util.List;

public class LinkeddExample {

    public static void main(String[] args) {

        List<String> myGroup=new LinkedList<>();  

        myGroup.add("Pohekar");  

        myGroup.add("Sumedh");  

        myGroup.add("Nikir");  

        System.out.println("Create Group: "+myGroup);  

        myGroup.remove("Pohekar");  

        System.out.println("Remove Group element: "+myGroup);  

        myGroup.set(1,"Niha");  

        System.out.println("Modify Group: "+myGroup);  

    }

}

 

Example of an ArrayList

import java.util.ArrayList;

import java.util.List;

public class ArrayListExca {

    public static void main(String[] args) {   

        List<String> Pro=new ArrayList<>();  

        Pro.add("PythonPro");  

        Pro.add("JavaPro");  

        Pro.add("C#Pro");  

          

        System.out.println("Traversing ArrayList...");  

        for(String s:Pro){  

            System.out.println(s);  

 

    }

    }

}

 

Keywords: ArrayList, LinkedList

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

157 Views