如何使用Apache Commons Collections创建一个新的MultiValueMap?

3
我需要一个能够容纳多个值的 TreeMap,因此我选择了 Commons Collections 4.0 中的 MultiValueMap

使用 HashMap 很容易。

 private MultiValueMap<String, Pair<Integer, String>> foo = 
    new MultiValueMap<String, Pair<Integer, String>>();

但是当我想使用其他地图实现,比如 TreeMap 时,构造函数变得相当笨拙。

//they hide MultiValueMap(Map map, Factory factory), 
//so I'll have to use static multiValueMap(...) instead

private MultiValueMap<String, Pair<Integer, String>> directoryMap=
    MultiValueMap.multiValueMap(new TreeMap<String, Pair<Integer, String>>());

现在,Eclipse 抛出了这个错误:

The method multiValueMap(Map<K,? super Collection<V>>) in the type MultiValueMap is not 
applicable for the arguments (TreeMap<String,Pair<Integer,String>>)

所以,我的问题是,Map<K,? super Collection<V>>是什么意思?

我尝试了new TreeMap<String, ArrayList<Pair<Integer, String>>>(),但那也不起作用。


你想要添加什么样的值到MultiValueMap中?此外,Pair是自定义类吗? - Sotirios Delimanolis
Pair只是您标准的Pair<K,V>对(它在commons lang中),我想要一个字符串键,它链接到多个“Pair”.... - tom91136
转移到TreeMap,它会删除所有重复的键。 - Kick
在TreeMap中,使用相同的键调用put()方法将覆盖旧值。 - tom91136
1个回答

3
我相信你应该使用 </p>
MultiValueMap.multiValueMap(
    new TreeMap<String, Collection<Pair<Integer, String>>>());

这并不是指ArrayList,因为库希望自由选择将哪个集合实现放入地图中。

(话虽如此:如果您使用GuavaMultimap,则可以在更简单的一行代码MultimapBuilder.treeKeys().arrayListValues().build()中获得此功能,并自动推断泛型。)


不是指ArrayList,因为库可能希望有选择的自由...实际上,默认情况下将使用ArrayList(请参阅javadoc)。要使用其他实现,请参见此问题 - Ryan Bennetts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接