Close

Java Collections - Collections.checkedMap() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

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.


Examples


Without using checkedMap

package com.logicbig.example.collections;

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

public class CheckedMapExample {

public static void main(String... args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
System.out.println(map);

Map map2 = map;
map2.put("two", 2);
System.out.println(map2);
}
}

Output

{1=one}
{1=one, two=2}




package com.logicbig.example.collections;

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

public class CheckedMapExample2 {

public static void main(String... args) {
Map<Integer, String> map = new HashMap<>();
map = Collections.checkedMap(map, Integer.class, String.class);
map.put(1, "one");
System.out.println(map);

Map map2 = map;
map2.put("two", 2);
System.out.println(map2);
}
}

Output

Caused by: java.lang.ClassCastException: Attempt to insert class java.lang.String key into map with key type class java.lang.Integer
at java.util.Collections$CheckedMap.typeCheck(Collections.java:3574)
at java.util.Collections$CheckedMap.put(Collections.java:3620)
at com.logicbig.example.collections.CheckedMapExample2.main(CheckedMapExample2.java:22)
... 6 more




See Also