Skip to content

Instantly share code, notes, and snippets.

@rschildmeijer
Created November 2, 2011 19:19
Show Gist options
  • Save rschildmeijer/1334603 to your computer and use it in GitHub Desktop.
Save rschildmeijer/1334603 to your computer and use it in GitHub Desktop.
defaultdict in java
public class DefaultHashMap<K, V> extends HashMap<K, V> {
private final Class<V> cls;
public DefaultHashMap(Class factory) {
this.cls = factory;
}
@Override
public V get(Object key) {
V value = super.get(key);
if (value == null) {
try {
value = cls.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
this.put((K) key, value);
}
return value;
}
public static void main(String[] args) {
Map<String, List<String>> dm = new DefaultHashMap<String, List<String>>(ArrayList.class);
dm.get("missing").add("roger");
dm.get("missing").add("roger2");
System.out.println(dm.get("missing"));
System.out.println(dm.get("missing2"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment