Differences between an ArrayList and a LinkedList in Java

DifferencesJavaObject Oriented ProgrammingProgramming

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

  • Elements can be inserted or accessed by their position in the list, using a zero-based index.

  • A list may contain duplicate elements.

  • In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table.

  • Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

Differences

Following are the important differences between ArrayList and LinkedList method.

Sr. No. Key ArrayList LinkedList
1 Internal Implementation ArrayList internally uses a dynamic array to store its elements. LinkedList uses Doubly Linked List to store its elements.
2 Manipulation ArrayList is slow as array manipulation is slower. LinkedList is faster being node based as not much bit shifting required.
3 Implementation ArrayList implements only List. LinkedList implements List as well as Queue. It can acts as a queue as well.
4 Access ArrayList is faster in storing and accessing data. LinkedList is faster in manipulation of data.

Example

Following example show how to use ArrayList and LinkedList −

JavaTester.java

import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class JavaTester { public static void main(String args[]) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); List<String> list1 = new LinkedList<>(); list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); System.out.println(list); System.out.println(list1); } }

Output

[A, B, C, D]
[A, B, C, D]

Example

Following example shows few additional methods that LinkedList have to work as queue whereas Arraylist doesn't have such methods as shown below −

JavaTester.java

import java.util.ArrayList; import java.util.LinkedList; public class JavaTester { public static void main(String args[]) { ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); System.out.println(list); LinkedList<String> list1 = new LinkedList<>(); list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); list1.removeFirst(); list1.removeLast(); System.out.println(list1); list1.addFirst("A"); list1.addLast("D"); System.out.println(list1); } }

Output

[A, B, C, D]
[B, C]
[A, B, C, D]

Both ArrayList and LinkedList are implementation of List interface in Java. Both classes are non-synchronized. Both can be used interchangably but ArrayList is preferred where read operations are high and LinkedList is preferred where insert operations are high.

raja
Updated on 19-Aug-2022 10:48:14

Advertisements