Home Java Collections Methods checkedMap() Java Collections checkedMap() Method 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.
Map<String, Integer> ages =
Collections.checkedMap(new TreeMap<String, Integer>(), String.class, Integer.class);
Map raw = ages;
raw.put("ben", "thirty"); // ClassCastException: bad value Call What 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.util.Collections
public static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType) Parameters Parameter Description 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 Value Description Map<K,V>A dynamically type-safe view of m.
Compare with Similar Methods Related wrappers:
Java Examples 1. Key and value 2. putAll 3. setValue Example 1 — Bad Values and Bad Keys Both Fail Insert a text age and a numeric name through a raw reference.
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);
}
} bad value: ClassCastException
bad key: ClassCastException
{ana=30} How It Works Two checks per put. The wrapper tests the key against String.class and the value against Integer.class.Each fails separately. "thirty" is not an Integer, and 7 is not a String, so both raw puts throw.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.
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);
}
} putAll: ClassCastException
stock: {apple=3} How It Works Incoming batch. Two good entries and one bad one (lime maps to a String).Validated first. The wrapper checks every entry before writing; "five" fails the value check.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.
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);
}
} setValue("one"): ClassCastException
{x=2} How It Works Wrapped entries. The checked map's entry set hands out entries that check their own setValue.Wrong value. Setting the text "one" fails, even though the raw entry type lets it compile.Right value. setValue(2) passes and updates the real map to x=2.Frequently Asked Questions What does Collections.checkedMap() do? It returns a Map view that verifies the key and value types of every mapping you insert, throwing ClassCastException for wrong types.
Is Map.Entry.setValue() checked? Yes. Entries obtained through entrySet() of the checked map check the new value.
Does a failed putAll() insert some entries? In current JDKs, no. All entries are checked before any is inserted.
Does checkedMap() allow null keys or values? The type check lets null through; the backing map decides whether null is allowed.
Which Java version added checkedMap()? Java 5.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion