Typed map in Java

Class definition:

public class TypedMap extends HashMap<String, Object> {
    public <T> T getTyped(String 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");

Leave a Reply

Your email address will not be published. Required fields are marked *