Collections public static Map unmodifiableMap(Map m) Method Example Program


Returns an unmodifiable view of the specified map

Program

package com.candidjava;

import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.unmodifiableMap(Map  m)
 *              method.
 */
public class CollectionsUnmodifiableMap {
	public static void main(String[] s) {
		Hashtable table = new Hashtable();
		table.put("key1", "karthik");
		table.put("key2", "mohan");
		table.put("key3", "kamal");
		System.out.println("Initial collection: " + table);
		Map m = Collections.unmodifiableMap(table);
		m.put("key3", "value3");
	}
}

Output

Exception in thread "main" Initial collection: {key3=kamal, key2=mohan, key1=karthik}
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Unknown Source)
at com.candidjava.CollectionsUnmodifiableMap.main(CollectionsUnmodifiableMap.java:22)

Explanation

public static Map unmodifiableMap(Map m)
Returns an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.
The returned map will be serializable if the specified map is serializable.

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


Related Post

Comments


©candidjava.com