How to Check If the Specified Map Is a Dynamically Typesafe View in Java

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);


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(
	at java.util.Collections$CheckedMap.put(
	at com.beginner.examples.CheckedMapExample.main(


Imported packages in Java documentation:

Notify of
Inline Feedbacks
View all comments