← Chapter 8 — Exceptions & Collections

31. Collections Framework

mixed

Description

The Collections Framework provides reusable structures for groups of objects. List keeps ordered items, Set avoids duplicates, and Map associates keys with values.

Generics declare the type a collection should hold. They let the compiler catch mixing an Integer into a list of String names.

Common Java collection interfaces and their purposes.
Common Java collection interfaces and their purposes.

Subtopics

List and Set

Description

List preserves order; Set keeps unique values.

Explanation

ArrayList is a common List implementation and HashSet is a common Set implementation.

Example

java.util.List<String> names = new java.util.ArrayList<>();

Map

Description

Map stores key-value pairs.

Explanation

A key identifies its associated value.

Example

java.util.Map<String, Integer> scores = new java.util.HashMap<>();

Explanation

Choose a collection based on the operations you need, not only its name. For example, use a Map when looking up Rohan's score by name is central to the task.

Example

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

public class CollectionDemo {
    public static void main(String[] args) {
        List<String> learners = new ArrayList<>();
        learners.add("Aditi");
        learners.add("Rohan");
        System.out.println(learners);
    }
}

Key points

  • List keeps ordered items.
  • Set rejects duplicate values.
  • Map stores key-value pairs.

Video

Open video

Open reference