Back to course

Working with the List Interface (ArrayList and LinkedList)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 37: Working with the List Interface

The List interface is the most commonly used collection. It guarantees ordered access and allows duplicates.

1. ArrayList

  • Implementation: Internally uses a dynamic array.
  • Performance: Excellent for random access (getting elements by index) but slower for insertions/deletions in the middle.

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

// List is the reference type, ArrayList is the implementation type (Polymorphism) List names = new ArrayList<>();

names.add("Bob"); names.add("Alice"); names.add("Bob"); // Duplicates allowed

System.out.println(names.get(1)); // Alice (Fast access) names.remove(0); // Removes Bob at index 0 (Potentially slow shift)

2. LinkedList

  • Implementation: Internally uses a doubly linked list structure.
  • Performance: Slower for random access (must traverse links) but extremely efficient for insertions/deletions at the start or middle.

java import java.util.LinkedList;

LinkedList ages = new LinkedList<>(); ages.add(10); ages.addFirst(5); // Efficient insertion at the beginning ages.removeLast(); // Efficient removal from the end

3. The Diamond Operator (<>)

In modern Java (JDK 7+), you can use the diamond operator (<>) instead of repeating the type argument on the right-hand side, improving readability.

java List names = new ArrayList<>(); // Equivalent to new ArrayList()