Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collections — collection algorithms and views

java.util.Collections provides static collection operations. Learn sorting, element swapping, and unmodifiable and synchronized views in Java SE 21.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Collections.sort(list);
Collections.sort(list, comparator);
Collections.unmodifiableList(list);
Collections.swap(list, i, j);
Collections.synchronizedMap(map);

java.util.Collections is a utility class, not a container; Collection is an interface.

Collections.sort stably sorts a list in place, naturally or using a Comparator. The list must support replacement, not necessarily resizing. Collections.swap exchanges two indexed elements; invalid indices cause IndexOutOfBoundsException.

Collections.unmodifiableList returns a view, not a copy. Backing-list changes remain visible; modifications through the view cause UnsupportedOperationException. Elements do not become immutable.

Collections.synchronizedMap returns a synchronized map view. Access only through it or its views. Wrap view iteration and compound operation sequences in synchronized (map), locking the returned map, not keySet() or entrySet().

Examples

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionsDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(3, 1, 2));
        Collections.sort(numbers);
        System.out.println(numbers);

        List<Integer> view = Collections.unmodifiableList(numbers);
        Collections.swap(numbers, 0, 2);
        System.out.println(view);

        try {
            view.add(4);
        } catch (UnsupportedOperationException ex) {
            System.out.println("Modification blocked");
        }

        Map<String, Integer> counts =
                Collections.synchronizedMap(new HashMap<>());
        counts.put("items", numbers.size());
        synchronized (counts) {
            for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }
        }
    }
}

Result

[1, 2, 3]
[3, 2, 1]
Modification blocked
items=3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources