Is it possible to have a HashMap
return a default value for all keys that are not found in the set?
You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:
public class DefaultHashMap extends HashMap {
public V getDefault(K key, V defaultValue) {
if (containsKey(key)) {
return get(key);
}
return defaultValue;
}
}
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).