HashMap to return default value for non-found keys?

后端 未结 14 2190
别跟我提以往
别跟我提以往 2020-11-27 14:05

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

14条回答
  •  感情败类
    2020-11-27 14:27

    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).

提交回复
热议问题