Created
December 12, 2012 16:37
-
-
Save marcomorain/4269328 to your computer and use it in GitHub Desktop.
A Java Map implementation that provides a default value.
This file contains hidden or 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.Collection; | |
| import java.util.Map; | |
| import java.util.Set; | |
| public class Maps { | |
| public static <K,V> Map<K,V> withDefaultValue(Map<K,V> map, V defaultValue){ | |
| return new DefaultMap<K, V>(map, defaultValue); | |
| } | |
| private static class DefaultMap<K, V> implements Map<K, V> { | |
| private final Map<K, V> map; | |
| private final V defaultValue; | |
| public DefaultMap(Map<K, V> map, V defaultValue) { | |
| this.map = map; | |
| this.defaultValue = defaultValue; | |
| } | |
| @Override | |
| public V get(Object key) { | |
| V ret = map.get(key); | |
| if (ret == null) { | |
| ret = defaultValue; | |
| } | |
| return ret; | |
| } | |
| @Override | |
| public int size() { | |
| return map.size(); | |
| } | |
| @Override | |
| public boolean isEmpty() { | |
| return map.isEmpty(); | |
| } | |
| @Override | |
| public boolean containsKey(Object o) { | |
| return map.containsKey(o); | |
| } | |
| @Override | |
| public boolean containsValue(Object o) { | |
| return map.containsValue(o); | |
| } | |
| @Override | |
| public V put(K k, V v) { | |
| return this.map.put(k, v); | |
| } | |
| @Override | |
| public V remove(Object o) { | |
| return map.remove(o); | |
| } | |
| @Override | |
| public void putAll(Map<? extends K, ? extends V> m) { | |
| this.map.putAll(m); | |
| } | |
| @Override | |
| public void clear() { | |
| this.map.clear(); | |
| } | |
| @Override | |
| public Set<K> keySet() { | |
| return this.map.keySet(); | |
| } | |
| @Override | |
| public Collection<V> values() { | |
| return this.map.values(); | |
| } | |
| @Override | |
| public Set<Map.Entry<K, V>> entrySet() { | |
| return this.map.entrySet(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment