Created
May 29, 2018 13:12
-
-
Save coltin/c8eec2d41ff915c6da0880c1137af847 to your computer and use it in GitHub Desktop.
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
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