Home Java Difference between ArrayList and LinkedList

Difference between ArrayList and LinkedList

0
696
java list

Get 30 minute iPhone repair with Puls! Schedule your repair now!

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

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

ArrayListLinkedList
ArrayList internally uses dynamic array to store the elements.LinkedList internally uses doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses 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 doubly linked list so no bit shifting is required in memory.
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.
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.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListIteration
{
    private static List<String> arrayList = new ArrayList<>();
    private static List<String> linkedList = new LinkedList<>();

    public static void initializeList(List<String> list, int bufferSize)
    {
        for (int i = 0; i < 50000; i++) { byte[] buffer = null; if (bufferSize > 0)
            {
                buffer = new byte[bufferSize];
            }
            String s = String.valueOf(i);
            list.add(s);
            // avoid buffer to be optimized away
            if (System.currentTimeMillis() == 0)
            {
                System.out.println(buffer);
            }
        }
    }

    public static void bench(List<String> list)
    {
        if (list.contains("bar"))
        {
            System.out.println("bar found");
        }
    }

    public static void main(String[] args) throws Exception
    {
        if (args.length != 2) return;
        
        int bufferSize = Integer.parseInt(args[0]);

        initializeList(arrayList, bufferSize);
        initializeList(linkedList, bufferSize);
        
        System.out.println("init done");
        
        System.out.println("ArrayList: " + arrayList);
        System.out.println("LinkedList: " + linkedList);

    }
}

Get 30 minute iPhone repair with Puls! Schedule your repair now!