Collections public static Set unmodifiableSet(Set s) Method Example Program


Returns an unmodifiable view of the specified set. 

Program

package com.candidjava;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.unmodifiableSet(Set <? extends T> s) method.
 */
public class CollectionsUnmodifiableSet {
	public static void main(String[] args) {
		Set<Character> set = new HashSet<Character>();
		set.add('X');
		set.add('Y');
		System.out.println("Initial list: " + set);
		Set<Character> immutableSet = Collections.unmodifiableSet(set);
		immutableSet.add('Z');
	}
}

Output

Initial list: [X, Y]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at com.candidjava.CollectionsUnmodifiableSet.main(CollectionsUnmodifiableSet.java:20)

Explanation

public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Returns an unmodifiable view of the specified set. This method allows modules to provide users with "read-only" access to internal sets. Query operations on the returned set "read through" to the specified set, and attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned set will be serializable if the specified set is serializable.

Parameters:
s - the set for which an unmodifiable view is to be returned.
Returns:
an unmodifiable view of the specified set.


Related Post

Comments


©candidjava.com