In this example, we will use Collections.checkedMap() to check if the specified map is a dynamically typesafe view.
Source Code
package com.beginner.examples;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CheckedMapExample {
public static void main(String a[]){
Map map = new HashMap();
map.put("java", "example");
Map checkedMap = Collections.checkedMap(map, String.class, String.class);
//you can add any type into map.
map.put("one", 1);
System.out.println("Checked map: " + checkedMap);
//you cannot add the wrong type into checkedMap.
checkedMap.put("one", 1);
}
}
Output:
Checked map: {java=example, one=1}
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer value into map with value type class java.lang.String
at java.util.Collections$CheckedMap.typeCheck(Collections.java:3577)
at java.util.Collections$CheckedMap.put(Collections.java:3620)
at com.beginner.examples.CheckedMapExample.main(CheckedMapExample.java:18)
References
Imported packages in Java documentation: