In Java, Collections.checkedSortedMap(m, keyType, valueType) returns a SortedMap wrapper that type-checks the key and value of every inserted mapping, while keeping firstKey(), lastKey(), and range views.
A TreeMap compares keys, so it sometimes notices a wrong key type, but it never looks at values. A wrong value type is caught only by the checked wrapper.
A static method of the java.util.Collections utility class, available since Java 5. Call it on the class name, as in Collections.checkedSortedMap(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the sorted map, key class, and value class.
Java
SortedMap<String, Double> prices = Collections.checkedSortedMap(
new TreeMap<String, Double>(), String.class, Double.class);
SortedMap raw = prices;
raw.put("cake", 4); // ClassCastException: Integer is not Double
Call
What it does
raw.put(k, v)
Key and value checked.
headMap / tailMap / subMap
Return checked sorted maps.
firstKey() / lastKey()
Same as the wrapped map.
Added in Java 5. Wrappers can be stacked; for example a synchronized wrapper around a checked one gives both thread safety and type checks.
Library declarations
Java
// java.util.Collections
public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
put(c, "3"): ClassCastException
{a=1, b=2}, lastKey b
How It Works
Layers. The outer synchronized wrapper takes a lock, then passes the call to the inner checked wrapper, which checks types before reaching the TreeMap.
Type check still applies. The value "3" is a String, so the inner layer throws.
Sorted reads. The valid entries print in key order and lastKey() is b.
Frequently Asked Questions
It returns a SortedMap view that checks the key and value types of every inserted mapping.
Only keys, indirectly, through comparisons. It never checks value types, which is where the wrapper helps most.
Yes. Sub-maps of the wrapper are checked sorted maps.
The literal 4 autoboxes to Integer. Use 4.0 so it boxes to Double.
Yes. Wrap the checked map in the synchronized one to get both behaviors.