Java Collections Framework Explained

The Java Collections Framework provides interfaces for groups of objects and implementations with different performance and ordering rules.

Lesson 51 of 127Intermediate14 min read

The Java Collections Framework provides interfaces for groups of objects and implementations with different performance and ordering rules. A List, Set, Queue and Map solve different problems. This overview helps you select a contract before choosing the concrete data structure that implements it.

Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.

Interfaces and implementations

The collections framework provides interfaces and implementations for groups of objects. List, Set and Queue are Collection subinterfaces; Map is a separate hierarchy.

Collection is the root interface for many element containers, but Map is a separate hierarchy that associates keys with values. List represents an ordered sequence and normally permits duplicates. Set represents uniqueness according to its equality or ordering contract. Queue describes processing order, often first-in-first-out, although priority queues use priority instead. The names describe semantics, not just alternative syntax for an array.

Collection semantics and interface-based variables

A List maintains positional order and allows duplicates. A Set represents uniqueness. A Queue describes processing order, which depends on its implementation.

Program to an interface when callers only need its published operations. List<String> names = new ArrayList<>() allows that variable to use the List contract while choosing array-backed storage. This does not make every implementation interchangeable in performance or optional operations. Some lists reject add, some reject null and some provide efficient random access while others do not.

Interface contracts and generic element types

Choose an interface for a variable and an implementation for creation. This lets the caller depend on required behavior rather than one concrete storage choice.

Generics let the compiler check element types. An untyped raw collection loses useful checks and can move a type error to runtime. Prefer specific element parameters and let ordinary autoboxing handle primitives when needed. Collection.size counts elements and is a method, unlike an array's length property. Collections store references, so adding an object does not automatically copy its state.

Implementation guarantees

Ordering, mutability, null support and thread safety vary by implementation. List.of creates an unmodifiable list and rejects null, while a new ArrayList is normally mutable.

Factory collections such as List.of and Set.of are unmodifiable, and they reject null. Set.of also rejects duplicate arguments. An ArrayList constructed from another collection is a mutable structural copy but still shares referenced elements. Iterator traversal is useful when removal must follow iterator rules, while stream operations offer a different style for transforming data without assuming every source can be modified.

Running the examples

Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.

How BookingCollections produces its output

The bookings ArrayList stores Lathe, Drill and Lathe as three positions, including a duplicate. Constructing LinkedHashSet from that sequence retains only the distinct names in first-occurrence order. The list's size remains three and the set's size is two. Printing both counts demonstrates that deduplication creates a separate collection rather than editing the original list.

How ListContract produces its output

ArrayList keeps the inserted sequence, including both East entries. Index one is the second position, which contains West. The List contract makes positional access meaningful, unlike a general Set. Duplicates remain because no operation in this example requests uniqueness.

How SetContract produces its output

The first add inserts East and returns true. The second equal value is already present, so add returns false and does not create a duplicate. LinkedHashSet preserves the insertion order of distinct values, which makes the final display predictable. A HashSet would still enforce uniqueness but would not promise that iteration order.

Separate interface semantics from implementation cost

A list promises positional sequence behavior, but that promise does not say every get call is equally cheap. ArrayList and LinkedList can produce identical output with very different traversal costs. Similarly, both HashSet and TreeSet enforce their own uniqueness rules, but one uses hashing and the other ordering comparisons. Begin with the required semantics: sequence, uniqueness, association or processing order. Then select an implementation based on lookup patterns, updates, memory and ordering. For practice, take a booking list and derive a unique insertion-ordered set without editing the list. Confirm both sizes and explain why the two collection structures serve different questions.

Collection and Collections name different APIs

Collection is an interface describing many element containers. Collections is a utility class with static operations such as sorting, reversing and creating wrappers. The similar spelling does not mean they are interchangeable types. Collections.unmodifiableList returns a backed view that refuses caller mutation, while changes to the original backing list can still be visible. List.copyOf instead creates an unmodifiable structural snapshot of its source elements and rejects null. Both still reference the supplied elements rather than deep-cloning them. Select a view when following internal changes is intended and a snapshot when later structural changes to the source should not affect the published collection.

Java Summary

  • The collections framework provides interfaces and implementations for groups of objects. List, Set and Queue are Collection subinterfaces; Map is a separate hierarchy.
  • A List maintains positional order and allows duplicates. A Set represents uniqueness. A Queue describes processing order, which depends on its implementation.
  • Choose an interface for a variable and an implementation for creation. This lets the caller depend on required behavior rather than one concrete storage choice.
  • Ordering, mutability, null support and thread safety vary by implementation. List.of creates an unmodifiable list and rejects null, while a new ArrayList is normally mutable.
  • Continue with Java exercises, Java quizzes and the Java study roadmap.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Java Collections Framework Explained in a complete program

Java
public class BookingCollections  {
    public static void main(String[] args)  {
        java.util.List<String> bookings = new java.util.ArrayList<>();
        bookings.add("Lathe");
        bookings.add("Drill");
        bookings.add("Lathe");
        java.util.Set<String> unique = new java.util.LinkedHashSet<>(bookings);
        System.out.println(bookings.size() + " bookings, " + unique.size() + " tools");
    }
}
Output
3 bookings, 2 tools
Line-by-line explanation
  1. Line 8Evaluates bookings.size() + " bookings, " + unique.size() + " tools" and prints 3 bookings, 2 tools.
Example 2

List preserves sequence and duplicates

Java
public class ListContract  {
    public static void main(String[] args)  {
        java.util.List<String> visits = new java.util.ArrayList<>();
        visits.add("East");
        visits.add("West");
        visits.add("East");
        System.out.println(visits);
        System.out.println(visits.get(1));
    }
}
Output
[East, West, East]
West
Line-by-line explanation
  1. Line 7Evaluates visits and prints [East, West, East].
  2. Line 8Evaluates visits.get(1) and prints West.
Example 3

A set can retain unique insertion order

Java
public class SetContract  {
    public static void main(String[] args)  {
        java.util.Set<String> zones = new java.util.LinkedHashSet<>();
        System.out.println(zones.add("East"));
        System.out.println(zones.add("East"));
        zones.add("West");
        System.out.println(zones);
    }
}
Output
true
false
[East, West]
Line-by-line explanation
  1. Line 4Evaluates zones.add("East") and prints true.
  2. Line 5Evaluates zones.add("East") and prints false.
  3. Line 7Evaluates zones and prints [East, West].

Java FAQ

Is Map a Collection?

No. Map is part of the Collections Framework but does not extend Collection. Its keySet, values and entrySet methods expose collection views of its associations. Those views have different element and uniqueness contracts.

Does an interface guarantee mutability?

No. Some operations are optional and may throw UnsupportedOperationException. A List can be mutable, fixed-size or unmodifiable. Choose or document the specific implementation and factory behavior when an operation needs structural changes.

Which collections are safe to use from several threads?

The ordinary java.util collections aren't. For shared data use the java.util.concurrent classes, such as ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentLinkedQueue and the BlockingQueue implementations, which are designed for concurrent access.

What is the difference between an unmodifiable view and an immutable copy?

Collections.unmodifiableList(list) is a read-only window onto the original list: callers can't change it through the view, but changes made to the original still show through. List.copyOf(list) makes a separate unmodifiable copy that never changes. In both cases the element objects themselves may still be mutable.

Can collections contain null?

It depends on the implementation. ArrayList, HashSet and HashMap accept null. Collections created with List.of, Set.of and Map.of reject it, and a TreeSet using natural ordering can't compare null. Avoiding null elements altogether keeps code simpler.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which contract permits duplicate positional elements?

Multiple choicemedium

Which framework type associates keys with values?

Java Quiz

2 questions to check what you learned.

  1. What does new ArrayList<>(source) copy?

    • The collection structure and element references
    • Every element's complete object graph
    • The source's later structural changes
  2. Does List.of support add?

    • No, it is unmodifiable
    • Yes, unless it contains strings
    • Only before get is called