本文介绍了向Guava Multimap中添加具有空值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个键添加到带有空集合作为值的Guava Multimap中.我该怎么做?

I have a need to add a key to a Guava Multimap with an empty collection as the value. How do I accomplish this?

我尝试过:

map.put( "my key", null );

但是调用get()返回一个包含一个元素的列表,该元素为null.我通过执行以下操作来解决此问题:

but calling get() returns a list with one element, which is null. I worked around this by doing the following:

map.putAll("my key2", new ArrayList())

但是我想知道这是否是一件坏事吗?我知道Guava在删除最后一个值时会自动删除一个键,以保持containsKey()的一致性.我这里最好的选择是什么?

but I'm wondering if this is a bad thing to do? I know Guava automatically removes a key when the last value is removed to keep containsKey() consistent. What's my best option here?

推荐答案

Multimap 故意禁止这种方法,并且您建议的解决方法是禁止操作-它实际上不会做任何事情

Multimap deliberately forbids this approach, and your proposed workaround is a no-op -- it won't actually do anything.

Multimap的工作方式是multimap.get(key)从不返回null,但始终返回某些集合-可能为空. (但是支持Multimap的实现可能实际上没有为该密钥存储任何内容,并且如果某个密钥未映射到 nonempty 集合,则它不会例如出现在keySet() . Multimap不是 a Map<K, Collection<V>> .)

The way Multimap works is that multimap.get(key) never returns null, but always returns some collection -- possibly empty. (But the backing Multimap implementation probably doesn't actually store anything for that key, and if a key isn't mapped to a nonempty collection, it won't e.g. appear in the keySet(). Multimap is not a Map<K, Collection<V>>.)

如果要映射到空集合,则必须使用Map<K, List<V>>.

If you want to map to an empty collection, you must use Map<K, List<V>>.

这篇关于向Guava Multimap中添加具有空值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:15