Difference Between ArrayList and LinkedList in Java — Java Technical Interview Questions & Answers

Difference Between ArrayList and LinkedList in Java

Difference Between ArrayList and LinkedList in Java

  • ArrayList is a resizable array: fast get(i), slower insert in the middle. LinkedList is a node chain: faster insert/delete at ends, slower random get(i).
  • Almost every fresher program should use ArrayList. Use LinkedList only when you truly insert/delete a lot at the ends.
  • Both implement List. Both allow duplicates and keep order. Pick by operation, not by name.
  • Let's take this on the board with one tiny Main class — no extra files. Difference Between ArrayList and LinkedList in Java — output: 2 then Asha. add Asha, add Ravi. size is 2. get(0) is Asha. get(2) would throw IndexOutOfBoundsException. Start from main, go line by line, and stop at each print. That output is the proof for Difference Between ArrayList and LinkedList.
  ArrayList names
    add("Asha")  add("Ravi")
         │
         ▼
    [0]=Asha  [1]=Ravi   size=2

Technical Interview Tip: Default ArrayList. LinkedList only if lots of insert/delete at ends. Say why get(i) differs.

Code Examples for Difference Between ArrayList and LinkedList in Java

Example

import java.util.ArrayList;

// ArrayList demo
public class Main {
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Asha");
    names.add("Ravi");
    System.out.println(names.size());
    System.out.println(names.get(0));
  }
}

Difference Between ArrayList and LinkedList in Java — output: 2 then Asha. add Asha, add Ravi. size is 2. get(0) is Asha. get(2) would throw IndexOutOfBoundsException.

How to Explain Difference Between ArrayList and LinkedList in Java to an Interviewer

Which is faster for get(i)?

ArrayList

When LinkedList?

Lots of insert/delete at ends