HashMap to return default value for non-found keys?

后端 未结 14 2200
别跟我提以往
别跟我提以往 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条回答
  •  萌比男神i
    2020-11-27 14:20

    [Update]

    As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...).

    [Original]

    There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:

    public class DefaultHashMap extends HashMap {
      protected V defaultValue;
      public DefaultHashMap(V defaultValue) {
        this.defaultValue = defaultValue;
      }
      @Override
      public V get(Object k) {
        return containsKey(k) ? super.get(k) : defaultValue;
      }
    }
    

提交回复
热议问题