Close

Java Collections - Collections.checkedSortedSet() Examples

[Last Updated: Dec 11, 2025]

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
                                                Class<E> type)

Returns a dynamically typesafe view of the specified SortedSet.


Examples


package com.logicbig.example.collections;

import java.util.*;

public class CheckedSortedSetExample {

public static void main(String... args) {
Comparator comparator = (o1, o2) -> 1;
SortedSet<Integer> set = new TreeSet<>(comparator);

set.add(1);
System.out.println(set);

Set set2 = set;
set2.add("two");
System.out.println(set2);
}
}

Output

[1]
[1, two]
JDK 25




Using checkedSortedSet

package com.logicbig.example.collections;

import java.util.*;

public class CheckedSortedSetExample2 {

public static void main(String... args) {
Comparator comparator = (o1, o2) -> 1;
SortedSet<Integer> set = new TreeSet<>(comparator);
set = Collections.checkedSortedSet(set, Integer.class);

set.add(1);
System.out.println(set);

Set set2 = set;
set2.add("two");
System.out.println(set2);
}
}

Output

[1]
java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
at java.util.Collections$CheckedCollection.typeCheck (Collections.java:3455)
at java.util.Collections$CheckedCollection.add (Collections.java:3503)
at com.logicbig.example.collections.CheckedSortedSetExample2.main (CheckedSortedSetExample2.java:22)
at jdk.internal.reflect.DirectMethodHandleAccessor.invoke (DirectMethodHandleAccessor.java:104)
at java.lang.reflect.Method.invoke (Method.java:565)
at org.codehaus.mojo.exec.AbstractExecJavaBase.executeMainMethod (AbstractExecJavaBase.java:402)
at org.codehaus.mojo.exec.ExecJavaMojo.executeMainMethod (ExecJavaMojo.java:142)
at org.codehaus.mojo.exec.AbstractExecJavaBase.doExecClassLoader (AbstractExecJavaBase.java:377)
at org.codehaus.mojo.exec.AbstractExecJavaBase.lambda$execute$0 (AbstractExecJavaBase.java:287)
at java.lang.Thread.run (Thread.java:1474)
JDK 25




See Also