返回默认值而不是null的Java Map实现 [英] Java Map implementation that returns a default value instead of null

查看:164
本文介绍了返回默认值而不是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).

这篇关于返回默认值而不是null的Java Map实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆