Collections static Map checkedMap(Map m,Class keyType,Class valueType)method Example Program


Returns a dynamically typesafe view of the specified map. Any attempt to insert a mapping whose key or value have the wrong type will result in an immediate ClassCastException. Similarly, any attempt to modify the value currently associated with a key will result in an immediate ClassCastException, whether the modification is attempted directly through the map itself, or through a Map.Entry instance obtained from the map's entry set view.

Program

package com.candidjava;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use Collections.checkedMap(Map
 *              <K,V> m, Class <K> keyType, Class <V> valueType) method.
 */
public class CheckedMap {
	public static void main(String args[]) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("1", "karthik");
		hmap.put("2", "mohan");
		hmap.put("3", "kamal");
		hmap.put("4", "hari");
		hmap.put("5", "vinodh");
		hmap.put("6", "anand");
		Map<String, String> tsmap = Collections.checkedMap(hmap, String.class,
				String.class);
		System.out.println(tsmap);
	}
}

Output

{1=karthik, 2=mohan, 3=kamal, 4=hari, 5=vinodh, 6=anand}

Explanation

public static <K,V> Map<K,V> checkedMap(Map<K,V> m,Class<K> keyType, Class<V> valueType)
Returns a dynamically typesafe view of the specified map. Any attempt to insert a mapping whose key or value have the wrong type will result in an immediate ClassCastException. Similarly, any attempt to modify the value currently associated with a key will result in an immediate ClassCastException, whether the modification is attempted directly through the map itself, or through a Map.Entry instance obtained from the map's entry set view.
Assuming a map contains no incorrectly typed keys or values prior to the time a dynamically typesafe view is generated, and that all subsequent access to the map takes place through the view (or one of its collection views), it is guaranteed that the map cannot contain an incorrectly typed key or value.

A discussion of the use of dynamically typesafe views may be found in the documentation for the checkedCollection method.

The returned map will be serializable if the specified map is serializable.

Since null is considered to be a value of any reference type, the returned map permits insertion of null keys or values whenever the backing map does.

Parameters:
m - the map for which a dynamically typesafe view is to be returned
keyType - the type of key that m is permitted to hold
valueType - the type of value that m is permitted to hold
Returns:
a dynamically typesafe view of the specified map
Since:
1.5


Related Post

Comments


©candidjava.com