从番石榴 (google) 中删除 Multimap 永远不会删除密钥本身。为什么?怎么办呢?
我正在使用番石榴的谷歌收藏库,我相信是最新版本。
我发现一旦我从给定 K 值的映射中删除最后一个 (K, V) 对,映射仍然包含 K 的条目,其中 V 是一个空集合。
我宁愿地图不包含此条目。为什么我无法删除它?或者,如果可以的话,怎样做?
这可能是我错过的简单事情。这是一个代码示例。谢谢。
// A plain ordinary map.
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
hm.put(1, 2);
hm.remove(1);
// Value of key 1 in HashMap: null
System.out.println("Value of key 1 in HashMap: " + hm.get(1));
// A list multimap.
ListMultimap<Integer, Integer> lmm = ArrayListMultimap.<Integer, Integer> create();
lmm.put(1, 2);
lmm.remove(1, 2);
// Value of key 1 in ArrayListMultiMap: []
System.out.println("Value of key 1 in ArrayListMultiMap: " + lmm.get(1));
// A set multimap.
SetMultimap<Integer, Integer> smm = HashMultimap.<Integer, Integer> create();
smm.put(1, 2);
smm.remove(1, 2);
// Value of key 1 in HashMultimap: []
System.out.println("Value of key 1 in HashMultimap: " + smm.get(1));
I'm using the google collections library from guava, I believe the most recent version.
I find that once I remove the final (K, V) pair from the map for a given value of K, the map still contains an entry for K, where V is an empty collection.
I would rather have the map not contain this entry. Why can't I remove it? Or, if I can, how?
It's probably something simple that I have missed. Here is a code example. Thanks.
// A plain ordinary map.
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
hm.put(1, 2);
hm.remove(1);
// Value of key 1 in HashMap: null
System.out.println("Value of key 1 in HashMap: " + hm.get(1));
// A list multimap.
ListMultimap<Integer, Integer> lmm = ArrayListMultimap.<Integer, Integer> create();
lmm.put(1, 2);
lmm.remove(1, 2);
// Value of key 1 in ArrayListMultiMap: []
System.out.println("Value of key 1 in ArrayListMultiMap: " + lmm.get(1));
// A set multimap.
SetMultimap<Integer, Integer> smm = HashMultimap.<Integer, Integer> create();
smm.put(1, 2);
smm.remove(1, 2);
// Value of key 1 in HashMultimap: []
System.out.println("Value of key 1 in HashMultimap: " + smm.get(1));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,当您删除多重映射中某个键的最后一个值时,该键就会从映射中删除。
例如,参见 'containsKey' 的行为,
但是当您从 multimap 获取值时,如果没有与该键关联的集合,它将返回一个空集合,请参见 AbstractMultimap 中 get 的实现:
Actually when you remove the last value for a key in the multimap, the key is removed from the map.
See for instance the behaviour of 'containsKey'
However when you get the values from the multimap, if there is no collection associated with the key, it will return an empty collection, see the implementation of get in AbstractMultimap:
要从
Multimap
中完全删除底层条目,您需要使用Map
视图:To totally remove the underlying entry from the
Multimap
, you need to use theMap
view: