Java Collections checkedMap() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 5+

Definition

In Java, Collections.checkedMap(m, keyType, valueType) returns a Map wrapper that checks both the key and the value of every mapping you add. A wrong type throws ClassCastException and the map stays unchanged.

The check covers put, putAll, Java 8 methods such as putIfAbsent and merge, and setValue on entries from entrySet().

A static method of the java.util.Collections utility class, available since Java 5. Call it on the class name, as in Collections.checkedMap(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Pass the map, the key class, and the value class.

Java
Map<String, Integer> ages =
    Collections.checkedMap(new TreeMap<String, Integer>(), String.class, Integer.class);
Map raw = ages;
raw.put("ben", "thirty");   // ClassCastException: bad value
CallWhat it does
raw.put(k, v)Key and value both checked.
putAll(other)Every entry checked before any is added.
entry.setValue(v)Checked through entrySet().
get / remove / containsKeyNot restricted.

Added in Java 5. Like the other checked wrappers, it is especially useful while hunting down which code inserts a bad mapping.

Library declarations
Java
// java.util.Collections
public static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)

Parameters

ParameterDescription
mThe map to protect.
keyTypeThe class every key must be an instance of.
valueTypeThe class every value must be an instance of.

Return Value

Return ValueDescription
Map<K,V>A dynamically type-safe view of m.

Compare with Similar Methods

Related wrappers:

MethodHow it differs
checkedSortedMap(m, k, v)Type-checked sorted map.
synchronizedMap(m)Thread-safe map; can wrap a checked map.
unmodifiableMap(m)No writes at all.

Java Examples

Example 1 — Bad Values and Bad Keys Both Fail

Insert a text age and a numeric name through a raw reference.

Java
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsCheckedMapPut {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        Map<String, Integer> ages = Collections.checkedMap(new TreeMap<String, Integer>(), String.class, Integer.class);
        ages.put("ana", 30);

        Map raw = ages;
        try {
            raw.put("ben", "thirty");
        } catch (ClassCastException e) {
            System.out.println("bad value: " + e.getClass().getSimpleName());
        }
        try {
            raw.put(7, 40);
        } catch (ClassCastException e) {
            System.out.println("bad key: " + e.getClass().getSimpleName());
        }
        System.out.println(ages);
    }
}

How It Works

  1. Two checks per put. The wrapper tests the key against String.class and the value against Integer.class.
  2. Each fails separately. "thirty" is not an Integer, and 7 is not a String, so both raw puts throw.
  3. Clean map. Only the valid entry ana=30 is stored.

Example 2 — One Bad Entry Stops the Whole putAll

Merge a raw map in which one value has the wrong type.

Java
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsCheckedMapPutAll {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        Map<String, Integer> stock = Collections.checkedMap(new TreeMap<String, Integer>(), String.class, Integer.class);
        stock.put("apple", 3);

        Map incoming = new TreeMap();
        incoming.put("kiwi", 4);
        incoming.put("lime", "five");
        incoming.put("pear", 6);
        try {
            stock.putAll(incoming);
        } catch (ClassCastException e) {
            System.out.println("putAll: " + e.getClass().getSimpleName());
        }
        System.out.println("stock: " + stock);
    }
}

How It Works

  1. Incoming batch. Two good entries and one bad one (lime maps to a String).
  2. Validated first. The wrapper checks every entry before writing; "five" fails the value check.
  3. Nothing merged. Not even kiwi, which sorts before lime, gets in; stock still holds only apple.

Example 3 — Entry.setValue Is Checked Too

Use a raw Map.Entry from entrySet() to change a value.

Java
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsCheckedMapEntry {
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        Map<String, Integer> m = Collections.checkedMap(new TreeMap<String, Integer>(), String.class, Integer.class);
        m.put("x", 1);

        for (Map.Entry e : m.entrySet()) {
            try {
                e.setValue("one");
            } catch (ClassCastException ex) {
                System.out.println("setValue(\"one\"): " + ex.getClass().getSimpleName());
            }
            e.setValue(2);
        }
        System.out.println(m);
    }
}

How It Works

  1. Wrapped entries. The checked map's entry set hands out entries that check their own setValue.
  2. Wrong value. Setting the text "one" fails, even though the raw entry type lets it compile.
  3. Right value. setValue(2) passes and updates the real map to x=2.

Frequently Asked Questions

It returns a Map view that verifies the key and value types of every mapping you insert, throwing ClassCastException for wrong types.
Yes. Entries obtained through entrySet() of the checked map check the new value.
In current JDKs, no. All entries are checked before any is inserted.
The type check lets null through; the backing map decides whether null is allowed.
Java 5.

Next: checkedNavigableMap()

Wrap a NavigableMap so inserts are type-checked while floorEntry and polling still work.

checkedNavigableMap() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful