Collections.checkedSet(Set, Class) in Java

Collections.checkedSet(Set, Class): This method is available in java.util.Collections class of Java.

Syntax:

<E> Set<E> java.util.Collections.checkedSet(Set<E> s, Class<E> type)

This method takes two arguments. This method returns a dynamically typesafe view of the specified set.

Note: Any attempt to insert an element of the wrong type will result inan immediate ClassCastException.

Parameters: Two parameters are required for this method.

s: the set for which a dynamically typesafe view is to be returned.

type: the type of element that s is permitted to hold.

Returns: a dynamically typesafe view of the specified set.

Exceptions: NA

Approach

Java

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

public class CollectionscheckedSet {
    public static void main(String[] args) {

        Set<Integer> set = new TreeSet<Integer>();
        set.add(10);
        set.add(12);
        set.add(10);
        set.add(14);
        System.out.println(Collections.checkedSet(set,
Integer.class));

    }
}

Output:

[10, 12, 14]


No comments:

Post a Comment