Java Collections checkedSortedSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 5+

Definition

In Java, Collections.checkedSortedSet(s, type) returns a SortedSet wrapper that type-checks every added element and keeps the sorted-set features: first(), last(), comparator(), and range views.

You might expect a TreeSet to catch wrong types on its own because it compares elements. It often does, but not always: the very first element of an empty TreeSet is only compared with itself, so a wrong type can slip in. The checked wrapper closes that gap.

A static method of the java.util.Collections utility class, available since Java 5. Call it on the class name, as in Collections.checkedSortedSet(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Pass the sorted set and the element class.

Java
SortedSet<Integer> ids = Collections.checkedSortedSet(new TreeSet<Integer>(), Integer.class);
SortedSet raw = ids;
raw.add("7");   // ClassCastException, even when the set is empty
CallWhat it does
raw.add(x)Checked before the tree sees it.
headSet / tailSet / subSetReturn checked views.
first() / last() / comparator()Same as the wrapped set.

Added in Java 5. Range views returned by the wrapper are themselves checked sorted sets, so they reject wrong types as well as out-of-range values.

Library declarations
Java
// java.util.Collections
public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)

Parameters

ParameterDescription
sThe sorted set to protect.
typeThe class every element must be an instance of.

Return Value

Return ValueDescription
SortedSet<E>A dynamically type-safe view of s.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
checkedNavigableSet(s, type)Adds navigation methods (Java 8).
checkedSet(s, type)Any set.
unmodifiableSortedSet(s)Read-only sorted view.

Java Examples

Example 1 — The First Element of an Empty TreeSet Is Not Type-Checked

A plain TreeSet<Integer> accepts a String as its first element. The checked version does not.

Java
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsCheckedSortedSetEmpty {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        SortedSet<Integer> plain = new TreeSet<>();
        SortedSet rawPlain = plain;
        rawPlain.add("7");
        System.out.println("plain accepted a String, size " + plain.size());
        try {
            System.out.println(plain.first() + 1);
        } catch (ClassCastException e) {
            System.out.println("plain fails on read: " + e.getClass().getSimpleName());
        }

        SortedSet<Integer> checked = Collections.checkedSortedSet(new TreeSet<Integer>(), Integer.class);
        SortedSet rawChecked = checked;
        try {
            rawChecked.add("7");
        } catch (ClassCastException e) {
            System.out.println("checked fails on add: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Self-comparison only. With no other elements, TreeSet compares "7" with itself, which works for a String, so it is stored.
  2. Time bomb. Reading first() as an Integer later throws, far from where the bad value entered.
  3. Wrapper checks the class. The checked set tests Integer.class.isInstance("7") before touching the tree and throws immediately.

Example 2 — headSet Rejects Wrong Types and Out-of-Range Values

A view below 10 accepts 5, rejects a String, and rejects 50 for a different reason.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsCheckedSortedSetRange {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        SortedSet<Integer> ids = Collections.checkedSortedSet(new TreeSet<>(Arrays.asList(3, 8, 12)), Integer.class);
        SortedSet<Integer> low = ids.headSet(10);

        SortedSet rawLow = low;
        try {
            rawLow.add("5");
        } catch (ClassCastException e) {
            System.out.println("\"5\": " + e.getClass().getSimpleName());
        }
        try {
            low.add(50);
        } catch (IllegalArgumentException e) {
            System.out.println("50: " + e.getClass().getSimpleName());
        }
        low.add(5);
        System.out.println("ids " + ids);
    }
}

How It Works

  1. Checked view. headSet(10) on the wrapper returns a checked sorted set, so the text "5" is refused with ClassCastException.
  2. Right type, wrong range. 50 is an Integer, but it lies outside "below 10", so the TreeSet view throws IllegalArgumentException.
  3. Valid insert. 5 passes both checks and appears in the full set between 3 and 8.

Example 3 — Custom Order Still Works Through the Wrapper

Wrap a reverse-ordered TreeSet and confirm that ordering and the comparator survive.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

public class CollectionsCheckedSortedSetOrder {
    public static void main(String[] args) {
        SortedSet<String> desc = Collections.checkedSortedSet(
            new TreeSet<String>(Collections.<String>reverseOrder()), String.class);
        desc.addAll(Arrays.asList("b", "a", "c"));

        System.out.println(desc + ", first " + desc.first() + ", last " + desc.last());
        System.out.println("comparator reverses? " + (desc.comparator().compare("a", "b") > 0));
    }
}

How It Works

  1. Checked addAll. All three letters are strings, so the batch passes the type check.
  2. Order from the tree. The reverse comparator puts c first and a last.
  3. Comparator exposed. comparator() returns the tree's comparator, which ranks "a" after "b" (a positive result).

Frequently Asked Questions

It returns a SortedSet view that throws ClassCastException when an element of the wrong type is added.
Usually, through comparison errors, but the first element of an empty TreeSet is only compared with itself, so a wrong type can get in. The wrapper checks every element.
Yes. Range views of the wrapper are checked sorted sets.
ClassCastException means the type is wrong; IllegalArgumentException from a range view means the value is outside its bounds.
Java 5.

Next: copy()

Copy one list into the start of another list.

copy() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful