Created
November 2, 2011 19:19
-
-
Save rschildmeijer/1334603 to your computer and use it in GitHub Desktop.
defaultdict in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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