问题描述
|
我使用的是来自番石榴的Google收藏库,我认为是最新版本。
我发现,一旦我从映射中删除了给定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));
解决方法
实际上,当您删除多重映射中某个键的最后一个值时,该键将从映射中移除。
例如查看\'containsKey \'的行为
System.out.println(\"ListMultimap contains key 1? \" + lmm.containsKey(1));
但是,当您从multimap获取值时,如果没有与键关联的集合,它将返回一个空集合,请参见AbstractMultimap中的get的实现:
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key,collection);
}
, 要从Multimap
中完全删除基础条目,您需要使用Map
视图:
multimap.asMap().remove(key);