Java ยท Chapter 34 of 42

Java Collections: List

The Collections Framework provides ready-made data structures. List is an ordered collection that allows duplicate elements, with ArrayList and LinkedList as the most common implementations.

ArrayList is backed by a resizable array (fast random access), while LinkedList is backed by a doubly linked list (fast insertion/removal at the ends).

Syntax
List<Type> list = new ArrayList<>();
list.add(value);

ArrayList basics

ArrayList grows dynamically, unlike arrays. Common methods include add(), get(), remove(), size(), and contains().

Choosing List implementations

Use ArrayList for frequent random access and iteration; use LinkedList when you need frequent insertions/removals at the beginning or middle.

Example 1 (java)
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    System.out.println(fruits);
    System.out.println(fruits.get(0));
  }
}
Output
[Apple, Banana]
Apple

add() appends elements, and get(0) retrieves the first element of the List.

Key points

  • List allows duplicate elements and maintains insertion order.
  • ArrayList is backed by a resizable array.
  • LinkedList is efficient for insertions/removals at the ends.
  • Common List methods: add, get, remove, size, contains.
๐Ÿ’ก Note: Always program against the List interface (`List<String> list = new ArrayList<>();`) for flexibility.

๐Ÿ“ Quick Quiz

1. Does List allow duplicate elements?

2. What backs ArrayList internally?

3. Which method retrieves an element by index in a List?