Month: February 2019

Typed map in Java

Class definition:

public class TypedMap extends HashMap {
    public  T getTyped(Object key) {
        return (T) super.get(key); //unchecked cast warning here
    }
}

Usage:

TypedMap map = new TypedMap();
map.put("string", "string");
map.put("boolean", true);
map.put("integer", 4);

Integer i = map.getTyped("integer");
String s = map.getTyped("string");
boolean b = map.getTyped("boolean");