为未找到的键返回默认值

为未找到的键返回默认值

本文介绍了HashMap 为未找到的键返回默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让 HashMap 为集合中未找到的所有键返回默认值?

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

推荐答案

[更新]

正如其他答案和评论者所指出的,从 Java 8 开始,您可以简单地调用 Map#getOrDefault(...).

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

[原文]

没有完全执行此操作的 Map 实现,但是通过扩展 HashMap 来实现您自己的实现是微不足道的:

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

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

这篇关于HashMap 为未找到的键返回默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:47