返回默认值而不是null的Java Map实现

问题描述:

我的代码中有一个 Map< String,List< String>> ,如果地图的,我会避免使用潜在的空指针#get()方法返回一个空列表而不是null。 java API中有这样的东西吗?我应该只扩展 HashMap

I have a Map<String, List<String>> in my code, where I'd avoid potential null pointers if the map's #get() method returned an empty list instead of null. Is there anything like this in the java API? Should I just extend HashMap?

@ Jon的答案是好的直接做你要求的方式。

@Jon's answer is a good way to do what you are asking directly.

但是我觉得你可能想要实现的是一个多图;即从键到值集合的映射。如果是这种情况,那么你还应该查看Guava或Apache commons集合中的multimap类。

But is strikes me that what you might be trying to implement is a "multimap"; i.e. a mapping from a key to a collection of values. If that is the case, then you should also look at the multimap classes in Guava or Apache commons collections.

看看:

  • the com.google.common.collect.Multimap interface and its implementations, or
  • the org.apache.commons.collections.MultiMap interface and its implementations.
  • the org.apache.commons.collections4.MultiMap interface and its implementations (a new version of the previous MultiMap; introduced in v4).