Skip to content

Instantly share code, notes, and snippets.

@coltin
Created May 29, 2018 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coltin/c8eec2d41ff915c6da0880c1137af847 to your computer and use it in GitHub Desktop.
Save coltin/c8eec2d41ff915c6da0880c1137af847 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
/**
* Useful when you want to do something like map.get(key).add(value). In this case you would add
* ArrayList::new and not have to check if there is already some ArrayList added as a key before
* adding it to the pool.
*/
public class DefaultHashMap<K, V> extends HashMap<K, V> {
private DefaultValueCreator<V> defaultValueCreator;
public DefaultHashMap(DefaultValueCreator<V> defaultValueCreator) {
this.defaultValueCreator = defaultValueCreator;
}
@Override
public V get(Object key) {
if (containsKey(key)) {
return super.get(key);
} else {
V newDefault = defaultValueCreator.createDefaultValue();
put((K) key, newDefault);
return newDefault;
}
}
public interface DefaultValueCreator<V> {
V createDefaultValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment