Close

Java Collections - Collections.checkedNavigableSet() Examples

Java Collections Java Java API 


Class:

java.util.Collections

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

Method:

public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
                                                      Class<E> type)

Returns a dynamically typesafe view of the specified NavigableSet.


Examples


package com.logicbig.example.collections;

import java.util.Comparator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;

public class CheckedNavigableSetExample {

public static void main(String... args) {
Comparator comparator = (o1, o2) -> 1;
NavigableSet<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]




Using checkedNavigableSet

package com.logicbig.example.collections;

import java.util.*;

public class CheckedNavigableSetExample2 {

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

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

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

Output

Caused by: 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:3037)
at java.util.Collections$CheckedCollection.add(Collections.java:3080)
at com.logicbig.example.collections.CheckedNavigableSetExample2.main(CheckedNavigableSetExample2.java:22)
... 6 more




See Also